/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.fzhucc.modules.sciTechnologyDemand.service;

import com.fzhucc.config.FileProperties;
import com.fzhucc.exception.BadRequestException;
import com.fzhucc.modules.Msg.domain.Msg;
import com.fzhucc.modules.Msg.domain.dto.SmallMsgDto;
import com.fzhucc.modules.Msg.repository.MsgRepository;
import com.fzhucc.modules.fenRecordLog.service.FenRecordLogService;
import com.fzhucc.modules.loveDemandRecord.domain.LoveDemandRecord;
import com.fzhucc.modules.loveDemandRecord.repository.LoveDemandRecordRepository;
import com.fzhucc.modules.loveModelRecord.domain.LoveModelRecord;
import com.fzhucc.modules.modelDemand.domain.ModelDemandAuditLog;
import com.fzhucc.modules.modelDemand.repository.ModelDemandAuditLogRepository;
import com.fzhucc.modules.sciCxResult.domain.SciCxResult;
import com.fzhucc.modules.sciCxResult.domain.SciCxResultInfo;
import com.fzhucc.modules.sciCxResult.domain.dto.SciCxResultDto;
import com.fzhucc.modules.sciEnterprise.domain.SciEnterprise;
import com.fzhucc.modules.sciEnterprise.repository.SciEnterpriseRepository;
import com.fzhucc.modules.sciEnterprise.service.mapstruct.SciEnterpriseMapper;
import com.fzhucc.modules.sciPersonnelInfo.domain.SciPersonnelInfo;
import com.fzhucc.modules.sciPersonnelInfo.domain.SciPersonnelInfoLesson;
import com.fzhucc.modules.sciPersonnelInfo.domain.SciPersonnelInfoResult;
import com.fzhucc.modules.sciPersonnelInfo.domain.SciPersonnelInfoWe;
import com.fzhucc.modules.sciPersonnelInfo.domain.dto.SciPersonnelInfoDto;
import com.fzhucc.modules.sciPersonnelInfo.repository.SciPersonnelInfoLessonRepository;
import com.fzhucc.modules.sciPersonnelInfo.repository.SciPersonnelInfoRepository;
import com.fzhucc.modules.sciPersonnelInfo.repository.SciPersonnelInfoResultRepository;
import com.fzhucc.modules.sciPersonnelInfo.repository.SciPersonnelInfoWeRepository;
import com.fzhucc.modules.sciPersonnelInfo.service.mapstruct.SciPersonnelInfoMapper;
import com.fzhucc.modules.sciStudio.domain.SciStudio;
import com.fzhucc.modules.sciStudio.domain.SciStudioImg;
import com.fzhucc.modules.sciStudio.domain.SciStudioInfo;
import com.fzhucc.modules.sciStudio.domain.dto.SciStudioDto;
import com.fzhucc.modules.sciStudio.domain.dto.SciStudioImgDto;
import com.fzhucc.modules.sciTdStatusLog.domain.SciTechnologyDemandPpLog;
import com.fzhucc.modules.sciTdStatusLog.repository.SciTechnologyDemandPpLogRepository;
import com.fzhucc.modules.sciTechnologyDemand.domain.SciTechnologyDemand;
import com.fzhucc.modules.sciTechnologyDemand.domain.SciTechnologyDemandInfo;
import com.fzhucc.modules.sciTechnologyDemand.domain.SciTechnologyDemandMate;
import com.fzhucc.modules.sciTechnologyDemand.domain.SciTechnologyDemandRecord;
import com.fzhucc.modules.sciTechnologyDemand.domain.dto.*;
import com.fzhucc.modules.sciTechnologyDemand.repository.SciTechnologyDemandInfoRepository;
import com.fzhucc.modules.sciTechnologyDemand.repository.SciTechnologyDemandMateRepository;
import com.fzhucc.modules.sciTechnologyDemand.repository.SciTechnologyDemandRecordRepository;
import com.fzhucc.modules.sciTechnologyDemand.service.mapstruct.SciTechnologyDemandInfoMapper;
import com.fzhucc.modules.sciTechnologyDemand.service.mapstruct.SciTechnologyDemandRecordMapper;
import com.fzhucc.modules.system.domain.User;
import com.fzhucc.modules.system.domain.UserSmall;
import com.fzhucc.modules.system.repository.UserRepository;
import com.fzhucc.modules.system.repository.UserSmallRepository;
import com.fzhucc.modules.system.service.DictDetailService;
import com.fzhucc.modules.system.service.DictService;
import com.fzhucc.modules.system.service.dto.DictDetailDto;
import com.fzhucc.modules.system.service.dto.DictDto;
import com.fzhucc.modules.system.service.dto.DictQueryCriteria;
import com.fzhucc.utils.*;
import io.swagger.annotations.ApiModelProperty;
import lombok.RequiredArgsConstructor;
import com.fzhucc.modules.sciTechnologyDemand.repository.SciTechnologyDemandRepository;
import com.fzhucc.modules.sciTechnologyDemand.service.mapstruct.SciTechnologyDemandMapper;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.sql.Timestamp;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
 * @author yyg
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2023-11-28
 **/
@Service
@RequiredArgsConstructor
public class SciTechnologyDemandService {

    private final SciTechnologyDemandRepository sciTechnologyDemandRepository;

    private final LoveDemandRecordRepository loveDemandRecordRepository;

    private final SciTechnologyDemandMateRepository sciTechnologyDemandMateRepository;

    private final SciTechnologyDemandRecordRepository sciTechnologyDemandRecordRepository;

    private final ModelDemandAuditLogRepository modelDemandAuditLogRepository;

    private final SciTechnologyDemandInfoRepository sciTechnologyDemandInfoRepository;
    private final SciTechnologyDemandMapper sciTechnologyDemandMapper;

    private final SciTechnologyDemandInfoMapper sciTechnologyDemandInfoMapper;

    private final DictService dictService;

    private final DictDetailService dictDetailService;

    private final UserRepository userRepository;

    private final MsgRepository msgRepository;

    private final UserSmallRepository userSmallRepository;

    private final SciEnterpriseRepository sciEnterpriseRepository;

    private final SciEnterpriseMapper sciEnterpriseMapper;

    private final SciPersonnelInfoMapper sciPersonnelInfoMapper;

    private final SciTechnologyDemandRecordMapper sciTechnologyDemandRecordMapper;

    private final FileProperties properties;

    private final SciPersonnelInfoRepository sciPersonnelInfoRepository;

    private final SciPersonnelInfoResultRepository sciPersonnelInfoResultRepository;

    private final SciPersonnelInfoLessonRepository sciPersonnelInfoLessonRepository;

    private final SciPersonnelInfoWeRepository sciPersonnelInfoWeRepository;

    private final SciTechnologyDemandPpLogRepository sciTechnologyDemandPpLogRepository;

    private final FenRecordLogService fenRecordLogService;

    @Value("${org.area.all}")
    public String all;

    @Value("${org.area.all2}")
    public String all2;

    @Value("${sci.audit.qxdsh}")
    public String qxdsh;

    @Value("${sci.audit.sjdsh}")
    public String sjdsh;

    @Value("${sci.audit.shtg}")
    public String shtg;

    @Value("${sci.audit.caogao}")
    public String caogao;

    @Value("${sci.audit.bh}")
    public String bh;

    @Value("${sci.doStatus}")
    public String ppz;

    @Value("${sci.doStatusypp}")
    public String ypp;

    @Value("${sci.doStatusyjj}")
    public String yjj;


    @Value("${sci.log.demand}")
    public String demand;

    @Value("${sci.stage.quPass}")
    public String quPass;

    @Value("${sci.stage.quNoPass}")
    public String quNoPass;

    @Value("${sci.stage.cityPass}")
    public String cityPass;

    @Value("${sci.stage.cityNoPass}")
    public String cityNoPass;

    @Value("${sci.log.model}")
    public String model;

    @Value("${fen.type.xq}")
    public String xq;

    public Map<String, Object> queryAll(SciTechnologyDemandQueryCriteria criteria, Pageable pageable) {
        //管理端根据登录用户地区
        String str = setCriteria(criteria);
        if (str == null) {
            if (criteria.getOrgAreas() != null && criteria.getOrgAreas().length > 0) {
                //表示为省总账号 且输入模糊查询
                //TODO 即查询参数有参数  省总账号查具体模糊查询
                String[] orgAreas = criteria.getOrgAreas();
                criteria.setOrgArea(orgAreas[orgAreas.length - 1]);
            } else {
                criteria.setOrgArea(str);
            }
        } else {
            //criteria.setOrgArea(str);
            //TODO 添加判断第三级   是否包含在第二级中   则采用第三级的查询
            if (criteria.getOrgAreas() != null && criteria.getOrgAreas().length == 3) {
                if (str.contains(criteria.getOrgAreas()[1])) {
                    criteria.setOrgArea(criteria.getOrgAreas()[2]);
                }
            } else {
                criteria.setOrgArea(str);
            }
        }
        criteria.setIsDelete(0);
        criteria.setOrgAreas(null);
        Page<SciTechnologyDemand> page = sciTechnologyDemandRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        Page<SciTechnologyDemandDto> map = page.map(sciTechnologyDemandMapper::toDto);
        List<SciTechnologyDemandDto> list = map.getContent();
        if (list != null && list.size() > 0) {
            for (SciTechnologyDemandDto sciTechnologyDemandDto : list) {
                //TODO 看是否登录没登录都返回未收藏
                try {
                    Long userId = SecurityUtils.getCurrentUserId();
                    if (userId != null) {
                        List<LoveDemandRecord> res = loveDemandRecordRepository.findByDemanIdAndUserId(userId, sciTechnologyDemandDto.getId());
                        if (res != null && res.size() > 0) {
                            sciTechnologyDemandDto.setIsLove(true);
                        }else{
                            sciTechnologyDemandDto.setIsLove(false);
                        }
                    } else {
                        sciTechnologyDemandDto.setIsLove(false);
                    }
                } catch (Exception e) {
                    sciTechnologyDemandDto.setIsLove(false);
                }
                //TODO 收藏的人数
                int loves = loveDemandRecordRepository.findByDemandId(sciTechnologyDemandDto.getId());
                sciTechnologyDemandDto.setLove(loves);

                String matype = sciTechnologyDemandDto.getMaType();
                if (matype != null && matype.contains(";")) {
                    String[] array = matype.split(";");
                    sciTechnologyDemandDto.setMatypes(array);
                } else {
                    String[] array = {};
                    sciTechnologyDemandDto.setMatypes(array);
                }
                String keyword = sciTechnologyDemandDto.getKeyword();
                if (keyword != null && keyword.contains(";")) {
                    String[] array = keyword.split(";");
                    sciTechnologyDemandDto.setKeywords(array);
                } else {
                    String[] array = {};
                    sciTechnologyDemandDto.setKeywords(array);
                }
                Integer qyId = sciTechnologyDemandDto.getQyId();
                if (qyId != null) {
                    Optional<SciEnterprise> res = sciEnterpriseRepository.findById(qyId);
                    if (res.isPresent()) {
                        SciEnterprise sciEnterprise = res.get();
                        sciTechnologyDemandDto.setQy(sciEnterpriseMapper.toDto(sciEnterprise));
                    }
                }
                String orgArea = sciTechnologyDemandDto.getOrgArea();
                if (orgArea != null && orgArea.contains(";")) {
                    String[] array = orgArea.split(";");
                    sciTechnologyDemandDto.setOrgAreas(array);
                } else {
                    String[] array = {};
                    sciTechnologyDemandDto.setOrgAreas(array);
                }

                String companyArea = sciTechnologyDemandDto.getCompanyArea();
                if (companyArea != null && companyArea.contains(";")) {
                    String[] array = companyArea.split(";");
                    sciTechnologyDemandDto.setCompanyAreas(array);
                } else {
                    String[] array = {};
                    sciTechnologyDemandDto.setCompanyAreas(array);
                }

                //todo 被选中的劳模工匠列表
                List<SciTechnologyDemandMate> isSelect = sciTechnologyDemandMateRepository.findIsSelect(sciTechnologyDemandDto.getId());
                List<SciPersonnelInfoDto> listSelectModels = new ArrayList<>();
                if (isSelect != null && isSelect.size() > 0) {
                    for (SciTechnologyDemandMate sciTechnologyDemandMate : isSelect) {
                        Integer spId = sciTechnologyDemandMate.getSpId();
                        Optional<SciPersonnelInfo> ops = sciPersonnelInfoRepository.findById(spId);
                        if (ops.isPresent()) {
                            SciPersonnelInfoDto sciPersonnelInfoDto = sciPersonnelInfoMapper.toDto(ops.get());

                            //劳模id
                            String matype2 = sciPersonnelInfoDto.getMatype();
                            if (matype2 != null && matype2.contains(";")) {
                                String[] array = matype2.split(";");
                                sciPersonnelInfoDto.setMatypes(array);
                            } else {
                                String[] array = {};
                                sciPersonnelInfoDto.setMatypes(array);
                            }
                            String retype = sciPersonnelInfoDto.getRetype();
                            if (retype != null && retype.contains(";")) {
                                String[] array = retype.split(";");
                                sciPersonnelInfoDto.setRetypes(array);
                            } else {
                                String[] array = {};
                                sciPersonnelInfoDto.setRetypes(array);
                            }
                            String keyword2 = sciPersonnelInfoDto.getKeyword();
                            if (keyword2 != null && keyword2.contains(";")) {
                                String[] array = keyword2.split(";");
                                sciPersonnelInfoDto.setKeywords(array);
                            } else {
                                String[] array = {};
                                sciPersonnelInfoDto.setKeywords(array);
                            }
                            String orgArea2 = sciPersonnelInfoDto.getOrgArea();
                            if (orgArea2 != null && orgArea2.contains(";")) {
                                String[] array = orgArea2.split(";");
                                sciPersonnelInfoDto.setOrgAreas(array);
                            } else {
                                String[] array = {};
                                sciPersonnelInfoDto.setOrgAreas(array);
                            }
                            Integer id = sciPersonnelInfoDto.getId();
                            List<SciPersonnelInfoResult> results = sciPersonnelInfoResultRepository.findBySpId(id);
                            sciPersonnelInfoDto.setListResult(results);
                            List<SciPersonnelInfoLesson> list2 = sciPersonnelInfoLessonRepository.findBySpId(id);
                            sciPersonnelInfoDto.setListLesson(list2);
                            List<SciPersonnelInfoWe> list3 = sciPersonnelInfoWeRepository.findBySpId(id);
                            sciPersonnelInfoDto.setListWe(list3);

                            List<ModelDemandAuditLog> modelDemandAuditLogs = modelDemandAuditLogRepository.findBySportdIdWithType(id, model);
                            sciPersonnelInfoDto.setListModelDemandAuditLog(modelDemandAuditLogs);

                            listSelectModels.add(sciPersonnelInfoDto);
                        }
                    }
                }
                sciTechnologyDemandDto.setListSelectModels(listSelectModels);


                List<ModelDemandAuditLog> modelDemandAuditLogs = modelDemandAuditLogRepository.findBySportdIdWithType(sciTechnologyDemandDto.getId(), demand);
                sciTechnologyDemandDto.setListModelDemandAuditLog(modelDemandAuditLogs);

                List<SciTechnologyDemandInfo> list2 = sciTechnologyDemandInfoRepository.findByTdId(sciTechnologyDemandDto.getId());
                List<SciTechnologyDemandInfoDto> list3 = sciTechnologyDemandInfoMapper.toDto(list2);
                if (list3 != null && list3.size() > 0) {
                    for (SciTechnologyDemandInfoDto info : list3) {
                        String maType = info.getMaType();
                        if (maType != null && maType.contains(";")) {
                            String[] array = maType.split(";");
                            info.setMaTypes(array);
                        } else {
                            String[] array = {};
                            info.setMaTypes(array);
                        }
                    }
                }
                sciTechnologyDemandDto.setListSdInfo(list3);

                List<SciTechnologyDemandRecord> list5 = sciTechnologyDemandRecordRepository.findByTdId(sciTechnologyDemandDto.getId());
                List<SciTechnologyDemandRecordDto> sciTechnologyDemandRecordDtos = sciTechnologyDemandRecordMapper.toDto(list5);
                sciTechnologyDemandDto.setListRecord(sciTechnologyDemandRecordDtos);
            }
        }
        return PageUtil.toPage(map);
    }

    public Map<String, Object> queryAllh5(SciTechnologyDemandQueryCriteria criteria, Pageable pageable) {
        //TODO 增加访问分数
        try {
            fenRecordLogService.insertUserFen(xq);
        } catch (Exception e) {

        }

        criteria.setIsDelete(0);
        if (criteria.getOrgArea() != null && criteria.getOrgArea().equals(all)) {
            //h5的直接传orgArea
            criteria.setOrgArea(null);
        }
        Page<SciTechnologyDemand> page = sciTechnologyDemandRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        Page<SciTechnologyDemandDto> map = page.map(sciTechnologyDemandMapper::toDto);
        List<SciTechnologyDemandDto> list = map.getContent();
        if (list != null && list.size() > 0) {
            for (SciTechnologyDemandDto sciTechnologyDemandDto : list) {
                //TODO 看是否登录没登录都返回未收藏
                try {
                    Long userId = SecurityUtils.getCurrentUserId();
                    if (userId != null) {
                        List<LoveDemandRecord> res = loveDemandRecordRepository.findByDemanIdAndUserId(userId, sciTechnologyDemandDto.getId());
                        if (res != null && res.size() > 0) {
                            sciTechnologyDemandDto.setIsLove(true);
                        }else{
                            sciTechnologyDemandDto.setIsLove(false);
                        }
                    } else {
                        sciTechnologyDemandDto.setIsLove(false);
                    }
                } catch (Exception e) {
                    sciTechnologyDemandDto.setIsLove(false);
                }
                //TODO 收藏的人数
                int loves = loveDemandRecordRepository.findByDemandId(sciTechnologyDemandDto.getId());
                sciTechnologyDemandDto.setLove(loves);

                String matype = sciTechnologyDemandDto.getMaType();
                if (matype != null && matype.contains(";")) {
                    String[] array = matype.split(";");
                    sciTechnologyDemandDto.setMatypes(array);
                } else {
                    String[] array = {};
                    sciTechnologyDemandDto.setMatypes(array);
                }
                String keyword = sciTechnologyDemandDto.getKeyword();
                if (keyword != null && keyword.contains(";")) {
                    String[] array = keyword.split(";");
                    sciTechnologyDemandDto.setKeywords(array);
                } else {
                    String[] array = {};
                    sciTechnologyDemandDto.setKeywords(array);
                }
                Integer qyId = sciTechnologyDemandDto.getQyId();
                if (qyId != null) {
                    Optional<SciEnterprise> res = sciEnterpriseRepository.findById(qyId);
                    if (res.isPresent()) {
                        SciEnterprise sciEnterprise = res.get();
                        sciTechnologyDemandDto.setQy(sciEnterpriseMapper.toDto(sciEnterprise));
                    }
                }
                String orgArea = sciTechnologyDemandDto.getOrgArea();
                if (orgArea != null && orgArea.contains(";")) {
                    String[] array = orgArea.split(";");
                    sciTechnologyDemandDto.setOrgAreas(array);
                } else {
                    String[] array = {};
                    sciTechnologyDemandDto.setOrgAreas(array);
                }

                String companyArea = sciTechnologyDemandDto.getCompanyArea();
                if (companyArea != null && companyArea.contains(";")) {
                    String[] array = companyArea.split(";");
                    sciTechnologyDemandDto.setCompanyAreas(array);
                } else {
                    String[] array = {};
                    sciTechnologyDemandDto.setCompanyAreas(array);
                }

                //todo 被选中的劳模工匠列表
                List<SciTechnologyDemandMate> isSelect = sciTechnologyDemandMateRepository.findIsSelect(sciTechnologyDemandDto.getId());
                List<SciPersonnelInfoDto> listSelectModels = new ArrayList<>();
                if (isSelect != null && isSelect.size() > 0) {
                    for (SciTechnologyDemandMate sciTechnologyDemandMate : isSelect) {
                        Integer spId = sciTechnologyDemandMate.getSpId();
                        Optional<SciPersonnelInfo> ops = sciPersonnelInfoRepository.findById(spId);
                        if (ops.isPresent()) {
                            SciPersonnelInfoDto sciPersonnelInfoDto = sciPersonnelInfoMapper.toDto(ops.get());

                            //劳模id
                            String matype2 = sciPersonnelInfoDto.getMatype();
                            if (matype2 != null && matype2.contains(";")) {
                                String[] array = matype2.split(";");
                                sciPersonnelInfoDto.setMatypes(array);
                            } else {
                                String[] array = {};
                                sciPersonnelInfoDto.setMatypes(array);
                            }
                            String retype = sciPersonnelInfoDto.getRetype();
                            if (retype != null && retype.contains(";")) {
                                String[] array = retype.split(";");
                                sciPersonnelInfoDto.setRetypes(array);
                            } else {
                                String[] array = {};
                                sciPersonnelInfoDto.setRetypes(array);
                            }
                            String keyword2 = sciPersonnelInfoDto.getKeyword();
                            if (keyword2 != null && keyword2.contains(";")) {
                                String[] array = keyword2.split(";");
                                sciPersonnelInfoDto.setKeywords(array);
                            } else {
                                String[] array = {};
                                sciPersonnelInfoDto.setKeywords(array);
                            }
                            String orgArea2 = sciPersonnelInfoDto.getOrgArea();
                            if (orgArea2 != null && orgArea2.contains(";")) {
                                String[] array = orgArea2.split(";");
                                sciPersonnelInfoDto.setOrgAreas(array);
                            } else {
                                String[] array = {};
                                sciPersonnelInfoDto.setOrgAreas(array);
                            }
                            Integer id = sciPersonnelInfoDto.getId();
                            List<SciPersonnelInfoResult> results = sciPersonnelInfoResultRepository.findBySpId(id);
                            sciPersonnelInfoDto.setListResult(results);
                            List<SciPersonnelInfoLesson> list2 = sciPersonnelInfoLessonRepository.findBySpId(id);
                            sciPersonnelInfoDto.setListLesson(list2);
                            List<SciPersonnelInfoWe> list3 = sciPersonnelInfoWeRepository.findBySpId(id);
                            sciPersonnelInfoDto.setListWe(list3);

                            List<ModelDemandAuditLog> modelDemandAuditLogs = modelDemandAuditLogRepository.findBySportdIdWithType(id, model);
                            sciPersonnelInfoDto.setListModelDemandAuditLog(modelDemandAuditLogs);

                            listSelectModels.add(sciPersonnelInfoDto);
                        }
                    }
                }
                sciTechnologyDemandDto.setListSelectModels(listSelectModels);


                List<ModelDemandAuditLog> modelDemandAuditLogs = modelDemandAuditLogRepository.findBySportdIdWithType(sciTechnologyDemandDto.getId(), demand);
                sciTechnologyDemandDto.setListModelDemandAuditLog(modelDemandAuditLogs);

                List<SciTechnologyDemandInfo> list2 = sciTechnologyDemandInfoRepository.findByTdId(sciTechnologyDemandDto.getId());
                List<SciTechnologyDemandInfoDto> list3 = sciTechnologyDemandInfoMapper.toDto(list2);
                if (list3 != null && list3.size() > 0) {
                    for (SciTechnologyDemandInfoDto info : list3) {
                        String maType = info.getMaType();
                        if (maType != null && maType.contains(";")) {
                            String[] array = maType.split(";");
                            info.setMaTypes(array);
                        } else {
                            String[] array = {};
                            info.setMaTypes(array);
                        }
                    }
                }
                sciTechnologyDemandDto.setListSdInfo(list3);

                List<SciTechnologyDemandRecord> list5 = sciTechnologyDemandRecordRepository.findByTdId(sciTechnologyDemandDto.getId());
                List<SciTechnologyDemandRecordDto> sciTechnologyDemandRecordDtos = sciTechnologyDemandRecordMapper.toDto(list5);
                sciTechnologyDemandDto.setListRecord(sciTechnologyDemandRecordDtos);
            }
        }
        return PageUtil.toPage(map);
    }

    public SciTechnologyDemandQueryCriteria doCriteria(SciTechnologyDemandQueryCriteria criteria) {
        if (criteria.getOrgArea() != null && !criteria.getOrgArea().equals("")) {
            //h5的直接传orgArea
            if (criteria.getOrgArea().equals(all)) {
                criteria.setOrgArea(null);
                if (criteria.getOrgAreas() != null && criteria.getOrgAreas().length > 0) {
                    //TODO 即查询参数有参数  省总账号查具体模糊查询
                    String[] orgAreas = criteria.getOrgAreas();
                    criteria.setOrgArea(orgAreas[orgAreas.length - 1]);
                }
            }
        } else {
            //管理端根据登录用户地区
            criteria.setOrgArea(setCriteria(criteria));
            if (criteria.getOrgAreas() != null && criteria.getOrgAreas().length > 0) {
                //TODO 即查询参数有参数  省总账号查具体模糊查询
                String[] orgAreas = criteria.getOrgAreas();
                //传参要查的 orgArea
                String csOrgArea = orgAreas[orgAreas.length - 1];
                //登录用户的 orgArea
                String dlOrgArea = criteria.getOrgArea();
                if (dlOrgArea == null) { //表示省总
                    criteria.setOrgArea(csOrgArea);
                } else {
                    //不是省总  登录的 存在  传进来的全部 则可以 否则则使用登录的
                    String[] split = dlOrgArea.split(";");
                    if (split.length == 1) {
                        //表示为省
                        if (split[0].equals(all)) {
                            criteria.setOrgArea(csOrgArea);
                        } else {
                            //其他省 则 传进来的第一个和这个省一致才返回数据
                            String orgArea = orgAreas[0];
                            if (split[0].equals(orgArea)) {
                                criteria.setOrgArea(csOrgArea);
                            } else {
                                criteria.setOrgArea(dlOrgArea);
                            }
                        }
                    }
                    if (split.length == 2) {
                        //例 ： 福建省;福州市;
                        String s = split[1];
                        if (orgAreas.length == 3) {
                            //福建省;福州市;马尾区;
                            String orgArea = orgAreas[1];
                            if (s.equals(orgArea)) {
                                //福州市相同的情况
                                criteria.setOrgArea(csOrgArea);
                            } else {
                                criteria.setOrgArea(dlOrgArea);
                            }
                        }
                        if (orgAreas.length == 2) {
                            //福建省;福州市;
                            String orgArea = orgAreas[1];
                            if (s.equals(orgArea)) {
                                //福州市相同的情况
                                criteria.setOrgArea(csOrgArea);
                            } else {
                                criteria.setOrgArea(dlOrgArea);
                            }
                        }
                    }
                    if (split.length == 3) {
                        //例 ： 福建省;福州市;马尾区;  相符就查马尾区  不相符就查登录用户的区域
                        String s = split[2];
                        if (s.equals(csOrgArea)) {
                            criteria.setOrgArea(csOrgArea);
                        } else {
                            criteria.setOrgArea(dlOrgArea);
                        }
                    }
                }
            }
        }
        criteria.setIsDelete(0);
        return criteria;
    }

    public DoStatusCountsDto queryAllByDoStatusCount(SciTechnologyDemandQueryCriteria criteria, Pageable pageable) {
        DoStatusCountsDto dto = new DoStatusCountsDto();
        SciTechnologyDemandQueryCriteria criteria1 = doCriteria(criteria);
        SciTechnologyDemandQueryCriteria criteria2 = criteria1;
        SciTechnologyDemandQueryCriteria criteria3 = criteria1;
        SciTechnologyDemandQueryCriteria criteria4 = criteria1;

        Pageable pageable1 = pageable;
        Pageable pageable2 = pageable;
        Pageable pageable3 = pageable;
        Pageable pageable4 = pageable;

        Page<SciTechnologyDemand> page = sciTechnologyDemandRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria1, criteriaBuilder), pageable1);
        Page<SciTechnologyDemandDto> map = page.map(sciTechnologyDemandMapper::toDto);
        dto.setAll(Integer.parseInt(Long.toString(map.getTotalElements())));

        criteria2.setDoStatus(ypp);
        Page<SciTechnologyDemand> page2 = sciTechnologyDemandRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria2, criteriaBuilder), pageable2);
        Page<SciTechnologyDemandDto> map2 = page2.map(sciTechnologyDemandMapper::toDto);
        dto.setYpp(Integer.parseInt(Long.toString(map2.getTotalElements())));

        criteria3.setDoStatus(ppz);
        Page<SciTechnologyDemand> page3 = sciTechnologyDemandRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria3, criteriaBuilder), pageable3);
        Page<SciTechnologyDemandDto> map3 = page3.map(sciTechnologyDemandMapper::toDto);
        dto.setPpz(Integer.parseInt(Long.toString(map3.getTotalElements())));

        criteria4.setDoStatus(yjj);
        Page<SciTechnologyDemand> page4 = sciTechnologyDemandRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria4, criteriaBuilder), pageable4);
        Page<SciTechnologyDemandDto> map4 = page4.map(sciTechnologyDemandMapper::toDto);
        dto.setYjj(Integer.parseInt(Long.toString(map4.getTotalElements())));

        //todo 修改 已匹配 = 已匹配 + 已解决
        int result = dto.getYpp() + dto.getYjj();
        dto.setYpp(result);
        return dto;
    }

    public List<SciTechnologyDemandDto> queryAllmy(SciTechnologyDemandQueryCriteria criteria) {
        //TODO 有传则用最后一个代替我的查询
        if (criteria.getOrgAreas() != null && criteria.getOrgAreas().length > 0) {
            String[] orgAreas = criteria.getOrgAreas();
            String csOrgArea = orgAreas[orgAreas.length - 1];
            criteria.setOrgArea(csOrgArea);
            criteria.setOrgAreas(null);
        }
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {
            throw new BadRequestException("未找到登录用户");
        }
        criteria.setUserId(userId);
        criteria.setIsDelete(0);
        List<SciTechnologyDemandDto> list = sciTechnologyDemandMapper.toDto(sciTechnologyDemandRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
        if (list != null && list.size() > 0) {
            for (SciTechnologyDemandDto sciTechnologyDemandDto : list) {
                //TODO 看是否登录没登录都返回未收藏
                try {
                    Long userId2 = SecurityUtils.getCurrentUserId();
                    if (userId2 != null) {
                        List<LoveDemandRecord> res = loveDemandRecordRepository.findByDemanIdAndUserId(userId2, sciTechnologyDemandDto.getId());
                        if (res != null && res.size() > 0) {
                            sciTechnologyDemandDto.setIsLove(true);
                        }else{
                            sciTechnologyDemandDto.setIsLove(false);
                        }
                    } else {
                        sciTechnologyDemandDto.setIsLove(false);
                    }
                } catch (Exception e) {
                    sciTechnologyDemandDto.setIsLove(false);
                }
                //TODO 收藏的人数
                int loves = loveDemandRecordRepository.findByDemandId(sciTechnologyDemandDto.getId());
                sciTechnologyDemandDto.setLove(loves);

                List<SciTechnologyDemandInfo> list2 = sciTechnologyDemandInfoRepository.findByTdId(sciTechnologyDemandDto.getId());
                List<SciTechnologyDemandInfoDto> list3 = sciTechnologyDemandInfoMapper.toDto(list2);
                if (list3 != null && list3.size() > 0) {
                    for (SciTechnologyDemandInfoDto info : list3) {
                        String maType = info.getMaType();
                        if (maType != null && maType.contains(";")) {
                            String[] array = maType.split(";");
                            info.setMaTypes(array);
                        } else {
                            String[] array = {};
                            info.setMaTypes(array);
                        }
                    }
                }
                sciTechnologyDemandDto.setListSdInfo(list3);

                List<SciTechnologyDemandRecord> list5 = sciTechnologyDemandRecordRepository.findByTdId(sciTechnologyDemandDto.getId());
                List<SciTechnologyDemandRecordDto> sciTechnologyDemandRecordDtos = sciTechnologyDemandRecordMapper.toDto(list5);
                sciTechnologyDemandDto.setListRecord(sciTechnologyDemandRecordDtos);
            }
        }
        return list;
    }

    public Map<String, Object> my(SciTechnologyDemandQueryCriteria criteria, Pageable pageable) {
        //TODO 有传则用最后一个代替我的查询
        if (criteria.getOrgAreas() != null && criteria.getOrgAreas().length > 0) {
            String[] orgAreas = criteria.getOrgAreas();
            String csOrgArea = orgAreas[orgAreas.length - 1];
            criteria.setOrgArea(csOrgArea);
            criteria.setOrgAreas(null);
        }
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {
            throw new BadRequestException("未找到登录用户");
        }
        criteria.setUserId(userId);
        criteria.setIsDelete(0);
        Page<SciTechnologyDemand> page = sciTechnologyDemandRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        Page<SciTechnologyDemandDto> map = page.map(sciTechnologyDemandMapper::toDto);
        List<SciTechnologyDemandDto> list = map.getContent();
        if (list != null && list.size() > 0) {
            for (SciTechnologyDemandDto sciTechnologyDemandDto : list) {
                //TODO 看是否登录没登录都返回未收藏
                try {
                    Long userId2 = SecurityUtils.getCurrentUserId();
                    if (userId2 != null) {
                        List<LoveDemandRecord> res = loveDemandRecordRepository.findByDemanIdAndUserId(userId2, sciTechnologyDemandDto.getId());
                        if (res != null && res.size() > 0) {
                            sciTechnologyDemandDto.setIsLove(true);
                        }else{
                            sciTechnologyDemandDto.setIsLove(false);
                        }
                    } else {
                        sciTechnologyDemandDto.setIsLove(false);
                    }
                } catch (Exception e) {
                    sciTechnologyDemandDto.setIsLove(false);
                }
                //TODO 收藏的人数
                int loves = loveDemandRecordRepository.findByDemandId(sciTechnologyDemandDto.getId());
                sciTechnologyDemandDto.setLove(loves);

                String matype = sciTechnologyDemandDto.getMaType();
                if (matype != null && matype.contains(";")) {
                    String[] array = matype.split(";");
                    sciTechnologyDemandDto.setMatypes(array);
                } else {
                    String[] array = {};
                    sciTechnologyDemandDto.setMatypes(array);
                }
                String keyword = sciTechnologyDemandDto.getKeyword();
                if (keyword != null && keyword.contains(";")) {
                    String[] array = keyword.split(";");
                    sciTechnologyDemandDto.setKeywords(array);
                } else {
                    String[] array = {};
                    sciTechnologyDemandDto.setKeywords(array);
                }
                Integer qyId = sciTechnologyDemandDto.getQyId();
                if (qyId != null) {
                    Optional<SciEnterprise> res = sciEnterpriseRepository.findById(qyId);
                    if (res.isPresent()) {
                        SciEnterprise sciEnterprise = res.get();
                        sciTechnologyDemandDto.setQy(sciEnterpriseMapper.toDto(sciEnterprise));
                    }
                }
                String orgArea = sciTechnologyDemandDto.getOrgArea();
                if (orgArea != null && orgArea.contains(";")) {
                    String[] array = orgArea.split(";");
                    sciTechnologyDemandDto.setOrgAreas(array);
                } else {
                    String[] array = {};
                    sciTechnologyDemandDto.setOrgAreas(array);
                }

                String companyArea = sciTechnologyDemandDto.getCompanyArea();
                if (companyArea != null && companyArea.contains(";")) {
                    String[] array = companyArea.split(";");
                    sciTechnologyDemandDto.setCompanyAreas(array);
                } else {
                    String[] array = {};
                    sciTechnologyDemandDto.setCompanyAreas(array);
                }

                List<ModelDemandAuditLog> modelDemandAuditLogs = modelDemandAuditLogRepository.findBySportdIdWithType(sciTechnologyDemandDto.getId(), demand);
                sciTechnologyDemandDto.setListModelDemandAuditLog(modelDemandAuditLogs);

                //todo 被选中的劳模工匠列表
                List<SciTechnologyDemandMate> isSelect = sciTechnologyDemandMateRepository.findIsSelect(sciTechnologyDemandDto.getId());
                List<SciPersonnelInfoDto> listSelectModels = new ArrayList<>();
                if (isSelect != null && isSelect.size() > 0) {
                    for (SciTechnologyDemandMate sciTechnologyDemandMate : isSelect) {
                        Integer spId = sciTechnologyDemandMate.getSpId();
                        Optional<SciPersonnelInfo> ops = sciPersonnelInfoRepository.findById(spId);
                        if (ops.isPresent()) {
                            SciPersonnelInfoDto sciPersonnelInfoDto = sciPersonnelInfoMapper.toDto(ops.get());

                            //劳模id
                            String matype2 = sciPersonnelInfoDto.getMatype();
                            if (matype2 != null && matype2.contains(";")) {
                                String[] array = matype2.split(";");
                                sciPersonnelInfoDto.setMatypes(array);
                            } else {
                                String[] array = {};
                                sciPersonnelInfoDto.setMatypes(array);
                            }
                            String retype = sciPersonnelInfoDto.getRetype();
                            if (retype != null && retype.contains(";")) {
                                String[] array = retype.split(";");
                                sciPersonnelInfoDto.setRetypes(array);
                            } else {
                                String[] array = {};
                                sciPersonnelInfoDto.setRetypes(array);
                            }
                            String keyword2 = sciPersonnelInfoDto.getKeyword();
                            if (keyword2 != null && keyword2.contains(";")) {
                                String[] array = keyword2.split(";");
                                sciPersonnelInfoDto.setKeywords(array);
                            } else {
                                String[] array = {};
                                sciPersonnelInfoDto.setKeywords(array);
                            }
                            String orgArea2 = sciPersonnelInfoDto.getOrgArea();
                            if (orgArea2 != null && orgArea2.contains(";")) {
                                String[] array = orgArea2.split(";");
                                sciPersonnelInfoDto.setOrgAreas(array);
                            } else {
                                String[] array = {};
                                sciPersonnelInfoDto.setOrgAreas(array);
                            }
                            Integer id = sciPersonnelInfoDto.getId();
                            List<SciPersonnelInfoResult> results = sciPersonnelInfoResultRepository.findBySpId(id);
                            sciPersonnelInfoDto.setListResult(results);
                            List<SciPersonnelInfoLesson> list2 = sciPersonnelInfoLessonRepository.findBySpId(id);
                            sciPersonnelInfoDto.setListLesson(list2);
                            List<SciPersonnelInfoWe> list3 = sciPersonnelInfoWeRepository.findBySpId(id);
                            sciPersonnelInfoDto.setListWe(list3);

                            List<ModelDemandAuditLog> modelDemandAuditLogs2 = modelDemandAuditLogRepository.findBySportdIdWithType(id, model);
                            sciPersonnelInfoDto.setListModelDemandAuditLog(modelDemandAuditLogs2);

                            listSelectModels.add(sciPersonnelInfoDto);
                        }
                    }
                }
                sciTechnologyDemandDto.setListSelectModels(listSelectModels);

                List<SciTechnologyDemandInfo> list2 = sciTechnologyDemandInfoRepository.findByTdId(sciTechnologyDemandDto.getId());
                List<SciTechnologyDemandInfoDto> list3 = sciTechnologyDemandInfoMapper.toDto(list2);
                if (list3 != null && list3.size() > 0) {
                    for (SciTechnologyDemandInfoDto info : list3) {
                        String maType = info.getMaType();
                        if (maType != null && maType.contains(";")) {
                            String[] array = maType.split(";");
                            info.setMaTypes(array);
                        } else {
                            String[] array = {};
                            info.setMaTypes(array);
                        }
                    }
                }
                sciTechnologyDemandDto.setListSdInfo(list3);

                List<SciTechnologyDemandRecord> list5 = sciTechnologyDemandRecordRepository.findByTdId(sciTechnologyDemandDto.getId());
                List<SciTechnologyDemandRecordDto> sciTechnologyDemandRecordDtos = sciTechnologyDemandRecordMapper.toDto(list5);
                sciTechnologyDemandDto.setListRecord(sciTechnologyDemandRecordDtos);
            }
        }
        return PageUtil.toPage(map);
    }

    //根据不同设置不同的部门查看
    public String setCriteria(SciTechnologyDemandQueryCriteria criteria) {
        Long userId = null;
        try {
            userId = SecurityUtils.getCurrentUserId();
        } catch (Exception e) {
            //throw new RuntimeException(e);
            String orgArea = criteria.getOrgArea();
            if (orgArea != null && (orgArea.equals(all) || orgArea.equals(all2))) { //如果等于福建省则查全部
                return null;
            }
        }
        if (userId != null) {
            Optional<User> userOptional = userRepository.findById(userId);
            User res = userOptional.get();
            if (res.getOrgArea() != null && (res.getOrgArea().equals(all) || res.getOrgArea().equals(all2))) {//用的org组织最高看全部
                return null;
            } else {
                return res.getOrgArea();//如果用户的权限不是福建省则 只能看到对应的组织
            }
        } else {
            return null;
        }
    }

    public String orgAreaReturn() {
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {//未登录则外面传进来
            return "";
        } else {
            Optional<User> userOptional = userRepository.findById(userId);
            User res = userOptional.get();
            return res.getOrgArea();
        }
    }

    public List<SciTechnologyDemandDto> queryAll(SciTechnologyDemandQueryCriteria criteria) {
        //导出  如果有传则按传的数组 导出
        criteria.setIsDelete(0);
        String str = setCriteria(criteria);
        if (str == null) {
            if (criteria.getOrgAreas() != null && criteria.getOrgAreas().length > 0) {
                //表示为省总账号 且输入模糊查询
                //TODO 即查询参数有参数  省总账号查具体模糊查询
                String[] orgAreas = criteria.getOrgAreas();
                criteria.setOrgArea(orgAreas[orgAreas.length - 1]);
            } else {
                criteria.setOrgArea(str);
            }
        } else {
            //criteria.setOrgArea(str);
            //TODO 添加判断第三级   是否包含在第二级中   则采用第三级的查询
            if (criteria.getOrgAreas() != null && criteria.getOrgAreas().length == 3) {
                if (str.contains(criteria.getOrgAreas()[1])) {
                    criteria.setOrgArea(criteria.getOrgAreas()[2]);
                }
            } else {
                criteria.setOrgArea(str);
            }
        }
        return sciTechnologyDemandMapper.toDto(sciTechnologyDemandRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Transactional
    public SciTechnologyDemandDto findById(Integer id) {
        //TODO 增加访问分数
        try {
            fenRecordLogService.insertUserFen(xq);
        } catch (Exception e) {

        }

        SciTechnologyDemand sciTechnologyDemand = sciTechnologyDemandRepository.findById(id).orElseGet(SciTechnologyDemand::new);
        ValidationUtil.isNull(sciTechnologyDemand.getId(), "SciTechnologyDemand", "id", id);
        //查询热度 +1
        Integer hot = sciTechnologyDemand.getHot();
        sciTechnologyDemand.setHot(hot + 1);
        SciTechnologyDemand save = sciTechnologyDemandRepository.save(sciTechnologyDemand);
        SciTechnologyDemandDto sciTechnologyDemandDto = sciTechnologyDemandMapper.toDto(save);
        List<SciTechnologyDemandInfo> list2 = sciTechnologyDemandInfoRepository.findByTdId(sciTechnologyDemandDto.getId());
        List<SciTechnologyDemandInfoDto> list3 = sciTechnologyDemandInfoMapper.toDto(list2);
        if (list3 != null && list3.size() > 0) {
            for (SciTechnologyDemandInfoDto info : list3) {
                String maType = info.getMaType();
                if (maType != null && maType.contains(";")) {
                    String[] array = maType.split(";");
                    info.setMaTypes(array);
                } else {
                    String[] array = {};
                    info.setMaTypes(array);
                }
            }
        }
        sciTechnologyDemandDto.setListSdInfo(list3);

        List<SciTechnologyDemandRecord> list5 = sciTechnologyDemandRecordRepository.findByTdId(sciTechnologyDemandDto.getId());
        List<SciTechnologyDemandRecordDto> sciTechnologyDemandRecordDtos = sciTechnologyDemandRecordMapper.toDto(list5);
        sciTechnologyDemandDto.setListRecord(sciTechnologyDemandRecordDtos);


        String matype = sciTechnologyDemandDto.getMaType();
        if (matype != null && matype.contains(";")) {
            String[] array = matype.split(";");
            sciTechnologyDemandDto.setMatypes(array);
        } else {
            String[] array = {};
            sciTechnologyDemandDto.setMatypes(array);
        }
        String keyword = sciTechnologyDemandDto.getKeyword();
        if (keyword != null && keyword.contains(";")) {
            String[] array = keyword.split(";");
            sciTechnologyDemandDto.setKeywords(array);
        } else {
            String[] array = {};
            sciTechnologyDemandDto.setKeywords(array);
        }
        Integer qyId = sciTechnologyDemandDto.getQyId();
        if (qyId != null) {
            Optional<SciEnterprise> res = sciEnterpriseRepository.findById(qyId);
            if (res.isPresent()) {
                SciEnterprise sciEnterprise = res.get();
                sciTechnologyDemandDto.setQy(sciEnterpriseMapper.toDto(sciEnterprise));
            }
        }
        String orgArea = sciTechnologyDemandDto.getOrgArea();
        if (orgArea != null && orgArea.contains(";")) {
            String[] array = orgArea.split(";");
            sciTechnologyDemandDto.setOrgAreas(array);
        } else {
            String[] array = {};
            sciTechnologyDemandDto.setOrgAreas(array);
        }

        String companyArea = sciTechnologyDemandDto.getCompanyArea();
        if (companyArea != null && companyArea.contains(";")) {
            String[] array = companyArea.split(";");
            sciTechnologyDemandDto.setCompanyAreas(array);
        } else {
            String[] array = {};
            sciTechnologyDemandDto.setCompanyAreas(array);
        }
        List<ModelDemandAuditLog> modelDemandAuditLogs = modelDemandAuditLogRepository.findBySportdIdWithType(sciTechnologyDemandDto.getId(), demand);
        sciTechnologyDemandDto.setListModelDemandAuditLog(modelDemandAuditLogs);

        //todo 被选中的劳模工匠列表
        List<SciTechnologyDemandMate> isSelect = sciTechnologyDemandMateRepository.findIsSelect(sciTechnologyDemandDto.getId());
        List<SciPersonnelInfoDto> listSelectModels = new ArrayList<>();
        if (isSelect != null && isSelect.size() > 0) {
            for (SciTechnologyDemandMate sciTechnologyDemandMate : isSelect) {
                Integer spId = sciTechnologyDemandMate.getSpId();
                Optional<SciPersonnelInfo> ops = sciPersonnelInfoRepository.findById(spId);
                if (ops.isPresent()) {
                    SciPersonnelInfoDto sciPersonnelInfoDto = sciPersonnelInfoMapper.toDto(ops.get());

                    //劳模id
                    String matype2 = sciPersonnelInfoDto.getMatype();
                    if (matype2 != null && matype2.contains(";")) {
                        String[] array = matype2.split(";");
                        sciPersonnelInfoDto.setMatypes(array);
                    } else {
                        String[] array = {};
                        sciPersonnelInfoDto.setMatypes(array);
                    }
                    String retype = sciPersonnelInfoDto.getRetype();
                    if (retype != null && retype.contains(";")) {
                        String[] array = retype.split(";");
                        sciPersonnelInfoDto.setRetypes(array);
                    } else {
                        String[] array = {};
                        sciPersonnelInfoDto.setRetypes(array);
                    }
                    String keyword2 = sciPersonnelInfoDto.getKeyword();
                    if (keyword2 != null && keyword2.contains(";")) {
                        String[] array = keyword2.split(";");
                        sciPersonnelInfoDto.setKeywords(array);
                    } else {
                        String[] array = {};
                        sciPersonnelInfoDto.setKeywords(array);
                    }
                    String orgArea2 = sciPersonnelInfoDto.getOrgArea();
                    if (orgArea2 != null && orgArea2.contains(";")) {
                        String[] array = orgArea2.split(";");
                        sciPersonnelInfoDto.setOrgAreas(array);
                    } else {
                        String[] array = {};
                        sciPersonnelInfoDto.setOrgAreas(array);
                    }
                    Integer myid = sciPersonnelInfoDto.getId();
                    List<SciPersonnelInfoResult> results = sciPersonnelInfoResultRepository.findBySpId(myid);
                    sciPersonnelInfoDto.setListResult(results);
                    List<SciPersonnelInfoLesson> list4 = sciPersonnelInfoLessonRepository.findBySpId(myid);
                    sciPersonnelInfoDto.setListLesson(list4);
                    List<SciPersonnelInfoWe> list6 = sciPersonnelInfoWeRepository.findBySpId(myid);
                    sciPersonnelInfoDto.setListWe(list6);

                    List<ModelDemandAuditLog> modelDemandAuditLogs2 = modelDemandAuditLogRepository.findBySportdIdWithType(myid, model);
                    sciPersonnelInfoDto.setListModelDemandAuditLog(modelDemandAuditLogs2);

                    listSelectModels.add(sciPersonnelInfoDto);
                }
            }
        }
        sciTechnologyDemandDto.setListSelectModels(listSelectModels);

        //TODO 看是否登录没登录都返回未收藏
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            if (userId != null) {
                List<LoveDemandRecord> res = loveDemandRecordRepository.findByDemanIdAndUserId(userId, sciTechnologyDemandDto.getId());
                if (res != null && res.size() > 0) {
                    sciTechnologyDemandDto.setIsLove(true);
                }else{
                    sciTechnologyDemandDto.setIsLove(false);
                }
            } else {
                sciTechnologyDemandDto.setIsLove(false);
            }
        } catch (Exception e) {
            sciTechnologyDemandDto.setIsLove(false);
        }
        //TODO 收藏的人数
        int loves = loveDemandRecordRepository.findByDemandId(sciTechnologyDemandDto.getId());
        sciTechnologyDemandDto.setLove(loves);


        List<Msg> listMsg = msgRepository.findNormalByGlIdWithAuditStatus(sciTechnologyDemandDto.getId(), "审核通过","%需求%");
        if (listMsg != null && listMsg.size() > 0) {
            List<SmallMsgDto> myList = new ArrayList<SmallMsgDto>();
            for (Msg msg : listMsg) {
                SmallMsgDto smallMsgDto = new SmallMsgDto();
                smallMsgDto.setId(msg.getId());
                smallMsgDto.setGlId(msg.getGlId());
                smallMsgDto.setType(msg.getType());
                smallMsgDto.setContext(msg.getContext());
                smallMsgDto.setAuditStatus(msg.getAuditStatus());
                smallMsgDto.setUserId(msg.getUserId());
                smallMsgDto.setUpdateBy(msg.getUpdateBy());
                smallMsgDto.setCreateTime(msg.getCreateTime());
                smallMsgDto.setCreateBy(msg.getCreateBy());
                smallMsgDto.setUpdateTime(msg.getUpdateTime());
                Optional<UserSmall> res = userSmallRepository.findById(msg.getUserId());
                if (res.isPresent()) {
                    smallMsgDto.setUserSmall(res.get());
                }
                myList.add(smallMsgDto);
            }
            sciTechnologyDemandDto.setMsgDto(myList);
        }
        return sciTechnologyDemandDto;
    }

    public SciTechnologyDemandDto create(SciTechnologyDemandAddDto dto) {
        String slogan = dto.getSlogan();
        if (slogan == null) {
            throw new BadRequestException("需求名称为空");
        }
        String companyName = dto.getCompanyName();
        /*if (companyName == null) {
            throw new BadRequestException("企业名称为空");
        }*/
        SciTechnologyDemand resources = new SciTechnologyDemand();
        resources.setPic(dto.getPic());
        resources.setCompanyName(companyName);
        resources.setSlogan(slogan);
        if (dto.getQyId() != null) {
            Integer qyId = dto.getQyId();
            Optional<SciEnterprise> res = sciEnterpriseRepository.findById(qyId);
            if (res.isPresent()) {
                SciEnterprise sciEnterprise = res.get();
                if (sciEnterprise.getIsDelete() == 1) {
                    throw new BadRequestException("该企业已被删除,请重新选择");
                } else {
                    resources.setQyId(sciEnterprise.getId());
                }
            } else {
                throw new BadRequestException("未找到该企业,请重新选择");
            }
        } else {
            resources.setQyId(null);
        }
        resources.setRegistrationTime(dto.getRegistrationTime());
        resources.setCompanyType(dto.getCompanyType());
        resources.setBusinessLicense(dto.getBusinessLicense());
        //resources.setCompanyArea(dto.getCompanyArea());
        if (dto.getCompanyAreas() != null && dto.getCompanyAreas().length > 0) {
            String last = "";
            for (String a : dto.getCompanyAreas()) {
                last = last + a + ";";
            }
            resources.setCompanyArea(last);
        } else {
            resources.setCompanyArea(null);
        }
        resources.setContacts(dto.getContacts());
        resources.setZscq(dto.getZscq());
        resources.setJjxc(dto.getJjxc());
        resources.setTsjn(dto.getTsjn());
        resources.setCxcg(dto.getCxcg());
        resources.setDoStatus(ppz);
        resources.setYq(dto.getYq());
        resources.setIsZxw(dto.getIsZxw());
        resources.setIsZj(dto.getIsZj());
        resources.setJoinModelCounts(dto.getJoinModelCounts());
        resources.setJjProblemType(dto.getJjProblemType());
        resources.setYjjProblemContext(dto.getYjjProblemContext());
        resources.setXy(dto.getXy());
        resources.setCz(dto.getCz());
        resources.setProfit(dto.getProfit());
        resources.setReview(dto.getReview());
        resources.setIsEdit(0);//设置默认添加不可编辑
        resources.setJobTitle(dto.getJobTitle());
        resources.setContactWay(dto.getContactWay());
        resources.setEmail(dto.getEmail());
        //resources.setRecord(dto.getRecord());
        resources.setHot(0);
        resources.setAddress(dto.getAddress());
        resources.setKeywordOther(dto.getKeywordOther());
        if (dto.getKeywords() != null && dto.getKeywords().length > 0) {
            String last = "";
            for (String a : dto.getKeywords()) {
                last = last + a + ";";
            }
            resources.setKeyword(last);
        } else {
            resources.setKeyword(null);
        }
        resources.setDetails(dto.getDetails());
        resources.setUserId(SecurityUtils.getCurrentUserId());
        resources.setFirstFinisherName(dto.getFirstFinisherName());
        resources.setUnitPosition(dto.getUnitPosition());
        if (dto.getMatypes() != null && dto.getMatypes().length > 0) {
            String last = "";
            for (String a : dto.getMatypes()) {
                last = last + a + ";";
            }
            resources.setMaType(last);
        } else {
            resources.setMaType(null);
        }
        resources.setIsDelete(0);
        resources.setIsShow(0);
        resources.setSort(1);
        resources.setAuditStatus(qxdsh);//区县待审核
        if (dto.getOrgAreas() != null && dto.getOrgAreas().length > 0) {
            //外部传
            String last = "";
            for (String a : dto.getOrgAreas()) {
                last = last + a + ";";
            }
            resources.setOrgArea(last);
        } else {
            //根据登录用户 orgArea进行判断
            resources.setOrgArea(orgAreaReturn());
        }
        resources.setTechnology(dto.getTechnology());
        resources.setRetype(dto.getRetype());
        resources.setHonor(dto.getHonor());
        //TODO 保存草稿
        if (dto.getAuditStatus() != null && dto.getAuditStatus().equals(caogao)) {//此状态为草稿
            String slogan2 = dto.getSlogan();
            if (slogan2 == null) {
                throw new BadRequestException("需求名称为空,请填写后保存草稿");
            }
            String companyName2 = dto.getCompanyName();
            /*if (companyName2 == null) {
                throw new BadRequestException("企业名称为空,请填写后保存草稿");
            }*/
            if (dto.getOrgAreas() == null) {
                throw new BadRequestException("请选择地区组织,再保存草稿");
            }
            if (dto.getOrgAreas().length == 0) {
                throw new BadRequestException("请选择地区组织,再保存草稿");
            }
            /*if (dto.getQyId() == null){
                throw new BadRequestException("请选择企业,再保存草稿");
            }*/
            //设置
            resources.setAuditStatus(caogao);
            resources.setIsEdit(1);//允许编辑
        }

        //TODO 如果企业id不为null的话则查询该企业表里信息替换原来所传参数
        if (resources.getQyId() != null) {
            Optional<SciEnterprise> res = sciEnterpriseRepository.findById(resources.getQyId());
            if (!res.isPresent()) {
                throw new BadRequestException("未查询到该企业,请选择企业");
            }
            SciEnterprise sciEnterprise = res.get();
            //resources.setOrgArea(sciEnterprise.getOrgArea());
            resources.setCompanyArea(sciEnterprise.getCompanyArea());
            resources.setBusinessLicense(sciEnterprise.getCode());
            resources.setYq(sciEnterprise.getDetailAddress());
            String nature = sciEnterprise.getNature();
            //"国有" "民营" "其他"
            if (nature == null) {
                resources.setCompanyType("其他");
            } else {
                if (nature.equals("GY")) {
                    resources.setCompanyType("国有");
                } else if (nature.equals("SY")) {
                    resources.setCompanyType("民营");
                } else {
                    resources.setCompanyType("其他");
                }
            }
        }
        SciTechnologyDemandDto sciTechnologyDemandDto = sciTechnologyDemandMapper.toDto(sciTechnologyDemandRepository.save(resources));

        SciTechnologyDemandPpLog sciTechnologyDemandPpLog = new SciTechnologyDemandPpLog();
        sciTechnologyDemandPpLog.setTdId(sciTechnologyDemandDto.getId());
        sciTechnologyDemandPpLog.setNewStatus(ppz);
        sciTechnologyDemandPpLog.setOldStatus("");//无 - 匹配中
        sciTechnologyDemandPpLogRepository.save(sciTechnologyDemandPpLog);

        //根据id设置sort
        Optional<SciTechnologyDemand> result = sciTechnologyDemandRepository.findById(sciTechnologyDemandDto.getId());
        if (result.isPresent()) {
            SciTechnologyDemand sciCxResult = result.get();
            sciCxResult.setSort(sciCxResult.getId());
            sciTechnologyDemandRepository.save(sciCxResult);
        }

        List<SciTechnologyDemandInfoAddDto> listSdInfo = dto.getListSdInfo();
        if (listSdInfo != null && listSdInfo.size() > 0) {
            for (SciTechnologyDemandInfoAddDto res : listSdInfo) {
                SciTechnologyDemandInfo sciTechnologyDemandInfo = new SciTechnologyDemandInfo();
                sciTechnologyDemandInfo.setUnitPosition(res.getUnitPosition());
                sciTechnologyDemandInfo.setFirstFinisherName(res.getFirstFinisherName());
                if (res.getMaTypes() != null && res.getMaTypes().length > 0) {
                    String last = "";
                    for (String a : res.getMaTypes()) {
                        last = last + a + ";";
                    }
                    sciTechnologyDemandInfo.setMaType(last);
                } else {
                    sciTechnologyDemandInfo.setMaType(null);
                }
                //sciTechnologyDemandInfo.setMaType(res.getMaType());
                sciTechnologyDemandInfo.setTdId(sciTechnologyDemandDto.getId());
                sciTechnologyDemandInfoRepository.save(sciTechnologyDemandInfo);
            }
        }

        List<SciTechnologyDemandRecordAddDto> listRecord = dto.getListRecord();
        if (listRecord != null && listRecord.size() > 0) {
            for (SciTechnologyDemandRecordAddDto res : listRecord) {
                SciTechnologyDemandRecord sciTechnologyDemandRecord = new SciTechnologyDemandRecord();
                sciTechnologyDemandRecord.setRecord(res.getRecord());
                sciTechnologyDemandRecord.setGjCounts(res.getGjCounts());
                sciTechnologyDemandRecord.setMyTime(res.getMyTime());
                sciTechnologyDemandRecord.setTdId(sciTechnologyDemandDto.getId());
                sciTechnologyDemandRecordRepository.save(sciTechnologyDemandRecord);
            }
        }
        String matype = sciTechnologyDemandDto.getMaType();
        if (matype != null && matype.contains(";")) {
            String[] array = matype.split(";");
            sciTechnologyDemandDto.setMatypes(array);
        } else {
            String[] array = {};
            sciTechnologyDemandDto.setMatypes(array);
        }
        List<SciTechnologyDemandInfo> list2 = sciTechnologyDemandInfoRepository.findByTdId(sciTechnologyDemandDto.getId());
        List<SciTechnologyDemandInfoDto> list3 = sciTechnologyDemandInfoMapper.toDto(list2);
        if (list3 != null && list3.size() > 0) {
            for (SciTechnologyDemandInfoDto info : list3) {
                String maType = info.getMaType();
                if (maType != null && maType.contains(";")) {
                    String[] array = maType.split(";");
                    info.setMaTypes(array);
                } else {
                    String[] array = {};
                    info.setMaTypes(array);
                }
            }
        }
        sciTechnologyDemandDto.setListSdInfo(list3);

        List<SciTechnologyDemandRecord> list5 = sciTechnologyDemandRecordRepository.findByTdId(sciTechnologyDemandDto.getId());
        List<SciTechnologyDemandRecordDto> sciTechnologyDemandRecordDtos = sciTechnologyDemandRecordMapper.toDto(list5);
        sciTechnologyDemandDto.setListRecord(sciTechnologyDemandRecordDtos);
        return sciTechnologyDemandDto;
    }

    public SciTechnologyDemandDto addWithSaveSciDraft(SciTechnologyDemandAddDto dto) {
        String slogan = dto.getSlogan();
        if (slogan == null) {
            throw new BadRequestException("需求名称为空,请填写后保存草稿");
        }
        String companyName = dto.getCompanyName();
        /*if (companyName == null) {
            throw new BadRequestException("企业名称为空,请填写后保存草稿");
        }*/
        if (dto.getOrgAreas() == null) {
            throw new BadRequestException("请选择地区组织,再保存草稿");
        }
        if (dto.getOrgAreas().length == 0) {
            throw new BadRequestException("请选择地区组织,再保存草稿");
        }
        SciTechnologyDemand resources = new SciTechnologyDemand();
        resources.setPic(dto.getPic());
        resources.setCompanyName(companyName);
        resources.setSlogan(slogan);
        resources.setRegistrationTime(dto.getRegistrationTime());
        resources.setCompanyType(dto.getCompanyType());
        resources.setBusinessLicense(dto.getBusinessLicense());
        //resources.setCompanyArea(dto.getCompanyArea());
        if (dto.getCompanyAreas() != null && dto.getCompanyAreas().length > 0) {
            String last = "";
            for (String a : dto.getCompanyAreas()) {
                last = last + a + ";";
            }
            resources.setCompanyArea(last);
        } else {
            resources.setCompanyArea(null);
        }
        resources.setContacts(dto.getContacts());
        resources.setZscq(dto.getZscq());
        resources.setJjxc(dto.getJjxc());
        resources.setTsjn(dto.getTsjn());
        resources.setCxcg(dto.getCxcg());
        resources.setDoStatus(ppz);
        resources.setYq(dto.getYq());
        resources.setIsZxw(dto.getIsZxw());
        resources.setIsZj(dto.getIsZj());
        resources.setJoinModelCounts(dto.getJoinModelCounts());
        resources.setJjProblemType(dto.getJjProblemType());
        resources.setYjjProblemContext(dto.getYjjProblemContext());
        resources.setXy(dto.getXy());
        resources.setCz(dto.getCz());
        resources.setProfit(dto.getProfit());
        resources.setReview(dto.getReview());
        resources.setIsEdit(1);//设置默认可编辑
        resources.setJobTitle(dto.getJobTitle());
        resources.setContactWay(dto.getContactWay());
        resources.setEmail(dto.getEmail());
        //resources.setRecord(dto.getRecord());
        resources.setHot(0);
        resources.setAddress(dto.getAddress());
        resources.setKeywordOther(dto.getKeywordOther());
        if (dto.getKeywords() != null && dto.getKeywords().length > 0) {
            String last = "";
            for (String a : dto.getKeywords()) {
                last = last + a + ";";
            }
            resources.setKeyword(last);
        } else {
            resources.setKeyword(null);
        }
        resources.setDetails(dto.getDetails());
        resources.setUserId(SecurityUtils.getCurrentUserId());
        resources.setFirstFinisherName(dto.getFirstFinisherName());
        resources.setUnitPosition(dto.getUnitPosition());
        if (dto.getMatypes() != null && dto.getMatypes().length > 0) {
            String last = "";
            for (String a : dto.getMatypes()) {
                last = last + a + ";";
            }
            resources.setMaType(last);
        } else {
            resources.setMaType(null);
        }
        resources.setIsDelete(0);
        resources.setIsShow(0);
        resources.setSort(1);
        resources.setAuditStatus(caogao);//草稿状态
        if (dto.getOrgAreas() != null && dto.getOrgAreas().length > 0) {
            //外部传
            String last = "";
            for (String a : dto.getOrgAreas()) {
                last = last + a + ";";
            }
            resources.setOrgArea(last);
        } else {
            //根据登录用户 orgArea进行判断
            resources.setOrgArea(orgAreaReturn());
        }
        resources.setTechnology(dto.getTechnology());
        resources.setRetype(dto.getRetype());
        resources.setHonor(dto.getHonor());
        SciTechnologyDemandDto sciTechnologyDemandDto = sciTechnologyDemandMapper.toDto(sciTechnologyDemandRepository.save(resources));

        SciTechnologyDemandPpLog sciTechnologyDemandPpLog = new SciTechnologyDemandPpLog();
        sciTechnologyDemandPpLog.setTdId(sciTechnologyDemandDto.getId());
        sciTechnologyDemandPpLog.setNewStatus(ppz);
        sciTechnologyDemandPpLog.setOldStatus("");//无 - 匹配中
        sciTechnologyDemandPpLogRepository.save(sciTechnologyDemandPpLog);

        //根据id设置sort
        Optional<SciTechnologyDemand> result = sciTechnologyDemandRepository.findById(sciTechnologyDemandDto.getId());
        if (result.isPresent()) {
            SciTechnologyDemand sciCxResult = result.get();
            sciCxResult.setSort(sciCxResult.getId());
            sciTechnologyDemandRepository.save(sciCxResult);
        }

        List<SciTechnologyDemandInfoAddDto> listSdInfo = dto.getListSdInfo();
        if (listSdInfo != null && listSdInfo.size() > 0) {
            for (SciTechnologyDemandInfoAddDto res : listSdInfo) {
                SciTechnologyDemandInfo sciTechnologyDemandInfo = new SciTechnologyDemandInfo();
                sciTechnologyDemandInfo.setUnitPosition(res.getUnitPosition());
                sciTechnologyDemandInfo.setFirstFinisherName(res.getFirstFinisherName());
                if (res.getMaTypes() != null && res.getMaTypes().length > 0) {
                    String last = "";
                    for (String a : res.getMaTypes()) {
                        last = last + a + ";";
                    }
                    sciTechnologyDemandInfo.setMaType(last);
                } else {
                    sciTechnologyDemandInfo.setMaType(null);
                }
                //sciTechnologyDemandInfo.setMaType(res.getMaType());
                sciTechnologyDemandInfo.setTdId(sciTechnologyDemandDto.getId());
                sciTechnologyDemandInfoRepository.save(sciTechnologyDemandInfo);
            }
        }

        List<SciTechnologyDemandRecordAddDto> listRecord = dto.getListRecord();
        if (listRecord != null && listRecord.size() > 0) {
            for (SciTechnologyDemandRecordAddDto res : listRecord) {
                SciTechnologyDemandRecord sciTechnologyDemandRecord = new SciTechnologyDemandRecord();
                sciTechnologyDemandRecord.setRecord(res.getRecord());
                sciTechnologyDemandRecord.setGjCounts(res.getGjCounts());
                sciTechnologyDemandRecord.setMyTime(res.getMyTime());
                sciTechnologyDemandRecord.setTdId(sciTechnologyDemandDto.getId());
                sciTechnologyDemandRecordRepository.save(sciTechnologyDemandRecord);
            }
        }
        String matype = sciTechnologyDemandDto.getMaType();
        if (matype != null && matype.contains(";")) {
            String[] array = matype.split(";");
            sciTechnologyDemandDto.setMatypes(array);
        } else {
            String[] array = {};
            sciTechnologyDemandDto.setMatypes(array);
        }
        List<SciTechnologyDemandInfo> list2 = sciTechnologyDemandInfoRepository.findByTdId(sciTechnologyDemandDto.getId());
        List<SciTechnologyDemandInfoDto> list3 = sciTechnologyDemandInfoMapper.toDto(list2);
        if (list3 != null && list3.size() > 0) {
            for (SciTechnologyDemandInfoDto info : list3) {
                String maType = info.getMaType();
                if (maType != null && maType.contains(";")) {
                    String[] array = maType.split(";");
                    info.setMaTypes(array);
                } else {
                    String[] array = {};
                    info.setMaTypes(array);
                }
            }
        }
        sciTechnologyDemandDto.setListSdInfo(list3);

        List<SciTechnologyDemandRecord> list5 = sciTechnologyDemandRecordRepository.findByTdId(sciTechnologyDemandDto.getId());
        List<SciTechnologyDemandRecordDto> sciTechnologyDemandRecordDtos = sciTechnologyDemandRecordMapper.toDto(list5);
        sciTechnologyDemandDto.setListRecord(sciTechnologyDemandRecordDtos);
        return sciTechnologyDemandDto;
    }

    public void updateDoStatus(SciTechnologyDemandEditDoStatusDto dto) {
        Integer id = dto.getId();
        Optional<SciTechnologyDemand> ops = sciTechnologyDemandRepository.findById(id);
        if (!ops.isPresent()) {
            throw new BadRequestException("未找到企业需求");
        }
        SciTechnologyDemand sciTechnologyDemand = ops.get();
        String olddoStatus = sciTechnologyDemand.getDoStatus();
        sciTechnologyDemand.setDoStatus(dto.getDoStatus());
        SciTechnologyDemand save = sciTechnologyDemandRepository.save(sciTechnologyDemand);


        SciTechnologyDemandPpLog sciTechnologyDemandPpLog = new SciTechnologyDemandPpLog();
        sciTechnologyDemandPpLog.setTdId(save.getId());
        sciTechnologyDemandPpLog.setNewStatus(save.getDoStatus());
        sciTechnologyDemandPpLog.setOldStatus(olddoStatus);//旧的到新的
        sciTechnologyDemandPpLogRepository.save(sciTechnologyDemandPpLog);
    }

    public void update(SciTechnologyDemandEditDto dto) {
        SciTechnologyDemand sciTechnologyDemand = sciTechnologyDemandRepository.findById(dto.getId()).orElseGet(SciTechnologyDemand::new);
        //TODO 如果编辑时为驳回状态则 调整为区县待审核
        if (sciTechnologyDemand.getAuditStatus().equals(bh)) {
            sciTechnologyDemand.setAuditStatus(qxdsh);
        }
        String olddoStatus = sciTechnologyDemand.getDoStatus();
        ValidationUtil.isNull(sciTechnologyDemand.getId(), "SciTechnologyDemand", "id", dto.getId());
        sciTechnologyDemand.setPic(dto.getPic());
        sciTechnologyDemand.setCompanyName(dto.getCompanyName());
        sciTechnologyDemand.setSlogan(dto.getSlogan());
        if (dto.getQyId() != null) {
            Integer qyId = dto.getQyId();
            Optional<SciEnterprise> res = sciEnterpriseRepository.findById(qyId);
            if (res.isPresent()) {
                SciEnterprise sciEnterprise = res.get();
                if (sciEnterprise.getIsDelete() == 1) {
                    throw new BadRequestException("该企业已被删除,请重新选择");
                } else {
                    sciTechnologyDemand.setQyId(sciEnterprise.getId());
                }
            } else {
                throw new BadRequestException("未找到该企业,请重新选择");
            }
        } else {
            sciTechnologyDemand.setQyId(null);
        }
        sciTechnologyDemand.setRegistrationTime(dto.getRegistrationTime());
        sciTechnologyDemand.setCompanyType(dto.getCompanyType());
        sciTechnologyDemand.setBusinessLicense(dto.getBusinessLicense());
        //sciTechnologyDemand.setCompanyArea(dto.getCompanyArea());
        if (dto.getCompanyAreas() != null && dto.getCompanyAreas().length > 0) {
            String last = "";
            for (String a : dto.getCompanyAreas()) {
                last = last + a + ";";
            }
            sciTechnologyDemand.setCompanyArea(last);
        } else {
            sciTechnologyDemand.setCompanyArea(null);
        }
        sciTechnologyDemand.setContacts(dto.getContacts());
        sciTechnologyDemand.setReview(dto.getReview());
        sciTechnologyDemand.setZscq(dto.getZscq());
        sciTechnologyDemand.setJjxc(dto.getJjxc());
        sciTechnologyDemand.setTsjn(dto.getTsjn());
        sciTechnologyDemand.setCz(dto.getCz());
        sciTechnologyDemand.setProfit(dto.getProfit());
        sciTechnologyDemand.setYq(dto.getYq());
        sciTechnologyDemand.setIsZxw(dto.getIsZxw());
        sciTechnologyDemand.setIsZj(dto.getIsZj());
        sciTechnologyDemand.setJoinModelCounts(dto.getJoinModelCounts());
        sciTechnologyDemand.setJjProblemType(dto.getJjProblemType());
        sciTechnologyDemand.setYjjProblemContext(dto.getYjjProblemContext());
        sciTechnologyDemand.setXy(dto.getXy());
        sciTechnologyDemand.setCxcg(dto.getCxcg());
        //sciTechnologyDemand.setRecord(dto.getRecord());
        sciTechnologyDemand.setJobTitle(dto.getJobTitle());
        sciTechnologyDemand.setContactWay(dto.getContactWay());
        sciTechnologyDemand.setEmail(dto.getEmail());
        sciTechnologyDemand.setKeywordOther(dto.getKeywordOther());
        if (dto.getKeywords() != null && dto.getKeywords().length > 0) {
            String last = "";
            for (String a : dto.getKeywords()) {
                last = last + a + ";";
            }
            sciTechnologyDemand.setKeyword(last);
        } else {
            sciTechnologyDemand.setKeyword(null);
        }
        sciTechnologyDemand.setDoStatus(dto.getDoStatus());
        sciTechnologyDemand.setAddress(dto.getAddress());
        sciTechnologyDemand.setDetails(dto.getDetails());
        //sciTechnologyDemand.setUserId(SecurityUtils.getCurrentUserId());
        sciTechnologyDemand.setFirstFinisherName(dto.getFirstFinisherName());
        sciTechnologyDemand.setUnitPosition(dto.getUnitPosition());
        if (dto.getMatypes() != null && dto.getMatypes().length > 0) {
            String last = "";
            for (String a : dto.getMatypes()) {
                last = last + a + ";";
            }
            sciTechnologyDemand.setMaType(last);
        } else {
            sciTechnologyDemand.setMaType(null);
        }
        sciTechnologyDemand.setIsDelete(dto.getIsDelete());
        //sciTechnologyDemand.setAuditStatus(dto.getAuditStatus());
        //sciTechnologyDemand.setSAuditStatus(dto.getSAuditStatus());
        sciTechnologyDemand.setIsShow(dto.getIsShow());
        sciTechnologyDemand.setSort(dto.getSort());
        if (dto.getOrgAreas() != null && dto.getOrgAreas().length > 0) {
            //外部传
            String last = "";
            for (String a : dto.getOrgAreas()) {
                last = last + a + ";";
            }
            sciTechnologyDemand.setOrgArea(last);
        } else {
            //根据登录用户 orgArea进行判断
            sciTechnologyDemand.setOrgArea(orgAreaReturn());
        }
        sciTechnologyDemand.setTechnology(dto.getTechnology());
        sciTechnologyDemand.setRetype(dto.getRetype());
        sciTechnologyDemand.setHonor(dto.getHonor());
        if (dto.getAuditStatus().equals(caogao) && sciTechnologyDemand.getAuditStatus().equals(qxdsh)) {
            throw new BadRequestException("当前状态为区县待审核,无法保存为草稿");
        } else if (dto.getAuditStatus().equals(caogao) && sciTechnologyDemand.getAuditStatus().equals(sjdsh)) {
            throw new BadRequestException("当前状态为市级待审核,无法保存为草稿");
        } else if (dto.getAuditStatus().equals(caogao) && sciTechnologyDemand.getAuditStatus().equals(bh)) {
            throw new BadRequestException("当前状态为驳回,无法保存为草稿");
        } else if (dto.getAuditStatus().equals(caogao) && sciTechnologyDemand.getAuditStatus().equals(shtg)) {
            throw new BadRequestException("当前状态为审核通过,无法保存为草稿");
        } else {
            //TODO 保存草稿
            if (dto.getAuditStatus().equals(caogao)) {//此状态为草稿
                String slogan2 = dto.getSlogan();
                if (slogan2 == null) {
                    throw new BadRequestException("需求名称为空,请填写后保存草稿");
                }
                String companyName2 = dto.getCompanyName();
                /*if (companyName2 == null) {
                    throw new BadRequestException("企业名称为空,请填写后保存草稿");
                }*/
                if (dto.getOrgAreas() == null) {
                    throw new BadRequestException("请选择地区组织,再保存草稿");
                }
                if (dto.getOrgAreas().length == 0) {
                    throw new BadRequestException("请选择地区组织,再保存草稿");
                }
                /*if (dto.getQyId() == null){
                    throw new BadRequestException("请选择企业,再保存草稿");
                }*/
                //设置
                sciTechnologyDemand.setAuditStatus(caogao);
                sciTechnologyDemand.setIsEdit(1);//允许编辑
            }
        }

        //TODO 表示取消草稿
        if ((sciTechnologyDemand.getAuditStatus().equals(caogao) && dto.getAuditStatus() == null) || (sciTechnologyDemand.getAuditStatus().equals(caogao) && !dto.getAuditStatus().equals(caogao))) {
            //设置
            sciTechnologyDemand.setAuditStatus(qxdsh);
            sciTechnologyDemand.setIsEdit(0);
        }


        //TODO 如果企业id不为null的话则查询该企业表里信息替换原来所传参数
        if (sciTechnologyDemand.getQyId() != null) {
            Optional<SciEnterprise> res = sciEnterpriseRepository.findById(sciTechnologyDemand.getQyId());
            if (!res.isPresent()) {
                throw new BadRequestException("未查询到该企业,请选择企业");
            }
            SciEnterprise sciEnterprise = res.get();
            //sciTechnologyDemand.setOrgArea(sciEnterprise.getOrgArea());
            sciTechnologyDemand.setCompanyArea(sciEnterprise.getCompanyArea());
            sciTechnologyDemand.setBusinessLicense(sciEnterprise.getCode());
            sciTechnologyDemand.setYq(sciEnterprise.getDetailAddress());
            String nature = sciEnterprise.getNature();
            //"国有" "民营" "其他"
            if (nature == null) {
                sciTechnologyDemand.setCompanyType("其他");
            } else {
                if (nature.equals("GY")) {
                    sciTechnologyDemand.setCompanyType("国有");
                } else if (nature.equals("SY")) {
                    sciTechnologyDemand.setCompanyType("民营");
                } else {
                    sciTechnologyDemand.setCompanyType("其他");
                }
            }
        }

        SciTechnologyDemand save = sciTechnologyDemandRepository.save(sciTechnologyDemand);

        SciTechnologyDemandPpLog sciTechnologyDemandPpLog = new SciTechnologyDemandPpLog();
        sciTechnologyDemandPpLog.setTdId(save.getId());
        sciTechnologyDemandPpLog.setNewStatus(save.getDoStatus());
        sciTechnologyDemandPpLog.setOldStatus(olddoStatus);//旧的到新的
        sciTechnologyDemandPpLogRepository.save(sciTechnologyDemandPpLog);

        List<SciTechnologyDemandInfoAddDto> listSdInfo = dto.getListSdInfo();
        if (listSdInfo != null && listSdInfo.size() > 0) {
            List<SciTechnologyDemandInfo> all2 = sciTechnologyDemandInfoRepository.findByTdId(save.getId());
            if (all2 != null && all2.size() > 0) {
                for (SciTechnologyDemandInfo result : all2) {
                    sciTechnologyDemandInfoRepository.deleteById(result.getId());
                }
            }
            for (SciTechnologyDemandInfoAddDto res : listSdInfo) {
                SciTechnologyDemandInfo sciTechnologyDemandInfo = new SciTechnologyDemandInfo();
                //sciTechnologyDemandInfo.setMaType(res.getMaType());
                if (res.getMaTypes() != null && res.getMaTypes().length > 0) {
                    String last = "";
                    for (String a : res.getMaTypes()) {
                        last = last + a + ";";
                    }
                    sciTechnologyDemandInfo.setMaType(last);
                } else {
                    sciTechnologyDemandInfo.setMaType(null);
                }
                sciTechnologyDemandInfo.setFirstFinisherName(res.getFirstFinisherName());
                sciTechnologyDemandInfo.setUnitPosition(res.getUnitPosition());
                sciTechnologyDemandInfo.setTdId(save.getId());
                sciTechnologyDemandInfoRepository.save(sciTechnologyDemandInfo);
            }
        }


        List<SciTechnologyDemandRecordAddDto> listRecord = dto.getListRecord();
        if (listRecord != null && listRecord.size() > 0) {
            List<SciTechnologyDemandRecord> all2 = sciTechnologyDemandRecordRepository.findByTdId(save.getId());
            if (all2 != null && all2.size() > 0) {
                for (SciTechnologyDemandRecord result : all2) {
                    sciTechnologyDemandRecordRepository.deleteById(result.getId());
                }
            }
            for (SciTechnologyDemandRecordAddDto res : listRecord) {
                SciTechnologyDemandRecord sciTechnologyDemandRecord = new SciTechnologyDemandRecord();
                sciTechnologyDemandRecord.setRecord(res.getRecord());
                sciTechnologyDemandRecord.setGjCounts(res.getGjCounts());
                sciTechnologyDemandRecord.setMyTime(res.getMyTime());
                sciTechnologyDemandRecord.setTdId(save.getId());
                sciTechnologyDemandRecordRepository.save(sciTechnologyDemandRecord);
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void auditSciTechnologyDemand(AuditSciTechnologyDemandDto dto) {
        Optional<SciTechnologyDemand> res = sciTechnologyDemandRepository.findById(dto.getId());
        if (!res.isPresent()) {
            throw new BadRequestException("未找到企业技术需求id");
        }
        String cAuditStatus = dto.getAuditStatus();
        if (cAuditStatus == null || cAuditStatus.equals("")) {
            throw new BadRequestException("缺少审核状态");
        }
        if (cAuditStatus.equals(caogao)) {
            throw new BadRequestException("状态为草稿状态,无法审核");
        }
        SciTechnologyDemand sciTechnologyDemand = res.get();
        //TODO 根据登录用户如果是市 的则审核市的字段    如果是区的则审核区的字段  admin暂不处理
        Long userId = SecurityUtils.getCurrentUserId();
        Optional<User> resUser = userRepository.findById(userId);
        if (!resUser.isPresent()) {
            throw new BadRequestException("未找到登录用户");
        }
        User user = resUser.get();
        String orgArea = user.getOrgArea();
        //TODO 如果orgArea里面有2个 ; 表示市级审核   3个; 表示区级审核  其他则不与通过
        if (orgArea == null || orgArea.equals("")) {
            throw new BadRequestException("缺少地区区域无法审核");
        }
        if (!orgArea.contains(";")) {
            throw new BadRequestException("地区区域不符合规范无法审核");
        }
        String[] results = orgArea.split(";");
        if (results.length == 1) {
            throw new BadRequestException("省级账号无法审核");
        } else if (results.length == 2) {
            if (cAuditStatus.equals(bh)) {//驳回
                if (!sciTechnologyDemand.getAuditStatus().equals(sjdsh)) {
                    throw new BadRequestException("区级审核未通过,无法操作");
                }
                //市级审核驳回 就变成区级待审核
                sciTechnologyDemand.setAuditStatus(qxdsh);
                sciTechnologyDemand.setIsEdit(1);//驳回设置为可编辑
                SciTechnologyDemand save = sciTechnologyDemandRepository.save(sciTechnologyDemand);

                ModelDemandAuditLog modelDemandAuditLog = new ModelDemandAuditLog();
                modelDemandAuditLog.setAdvice(dto.getAdvice());//市审核驳回建议
                modelDemandAuditLog.setType(demand);
                modelDemandAuditLog.setStage(cityNoPass);
                modelDemandAuditLog.setSportdid(save.getId());
                modelDemandAuditLogRepository.save(modelDemandAuditLog);
            } else if (cAuditStatus.equals(shtg)) {
                if (!sciTechnologyDemand.getAuditStatus().equals(sjdsh)) {
                    throw new BadRequestException("区级审核未通过,无法操作");
                }
                //区级审核通过 市级审核通过则通过
                sciTechnologyDemand.setAuditStatus(shtg);
                if (sciTechnologyDemand.getIsEdit() == 1) {

                } else {
                    sciTechnologyDemand.setIsEdit(0); //打开了允许编辑就不管他 否住则设置为不可编辑
                }
                //审核通过设为显示
                sciTechnologyDemand.setIsShow(1);
                SciTechnologyDemand save = sciTechnologyDemandRepository.save(sciTechnologyDemand);

                ModelDemandAuditLog modelDemandAuditLog = new ModelDemandAuditLog();
                modelDemandAuditLog.setAdvice(dto.getAdvice());//市审核通过建议
                modelDemandAuditLog.setType(demand);
                modelDemandAuditLog.setStage(cityPass);
                modelDemandAuditLog.setSportdid(save.getId());
                modelDemandAuditLogRepository.save(modelDemandAuditLog);
            } else {
                throw new BadRequestException("未符合规范的类型,无法审核");
            }
        } else if (results.length == 3) {
            if (cAuditStatus.equals(bh)) {//驳回
                //区级审核
                sciTechnologyDemand.setIsEdit(1);//驳回设置为可编辑
                sciTechnologyDemand.setAuditStatus(cAuditStatus);
                SciTechnologyDemand save = sciTechnologyDemandRepository.save(sciTechnologyDemand);

                ModelDemandAuditLog modelDemandAuditLog = new ModelDemandAuditLog();
                modelDemandAuditLog.setAdvice(dto.getAdvice());//市审核通过建议
                modelDemandAuditLog.setType(demand);
                modelDemandAuditLog.setStage(quNoPass);
                modelDemandAuditLog.setSportdid(save.getId());
                modelDemandAuditLogRepository.save(modelDemandAuditLog);
            } else if (cAuditStatus.equals(shtg)) {
                //区级审核通过 变为市级待审核
                sciTechnologyDemand.setAuditStatus(sjdsh);
                if (sciTechnologyDemand.getIsEdit() == 1) {

                } else {
                    sciTechnologyDemand.setIsEdit(0); //打开了允许编辑就不管他 否住则设置为不可编辑
                }
                SciTechnologyDemand save = sciTechnologyDemandRepository.save(sciTechnologyDemand);

                ModelDemandAuditLog modelDemandAuditLog = new ModelDemandAuditLog();
                modelDemandAuditLog.setAdvice(dto.getAdvice());//市审核通过建议
                modelDemandAuditLog.setType(demand);
                modelDemandAuditLog.setStage(quPass);
                modelDemandAuditLog.setSportdid(save.getId());
                modelDemandAuditLogRepository.save(modelDemandAuditLog);
            } else {
                throw new BadRequestException("未符合规范的类型,无法审核");
            }
        } else {
            throw new BadRequestException("未符合的审级权限无法审核");
        }
    }


    @Transactional(rollbackFor = Exception.class)
    public void isAllowEdit(AllowSciTechnologyDemandDto dto) {
        Optional<SciTechnologyDemand> res = sciTechnologyDemandRepository.findById(dto.getId());
        if (!res.isPresent()) {
            throw new BadRequestException("未找到企业技术需求id");
        }
        Integer isEdit = dto.getIsEdit();
        if (isEdit == null) {
            throw new BadRequestException("缺少参数");
        }
        if (isEdit != 0 && isEdit != 1) {
            throw new BadRequestException("参数错误无法操作");
        }
        SciTechnologyDemand sciTechnologyDemand = res.get();
        sciTechnologyDemand.setIsEdit(isEdit);
        sciTechnologyDemandRepository.save(sciTechnologyDemand);
    }

    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            //假删除
            //sciTechnologyDemandRepository.deleteById(id);
            Optional<SciTechnologyDemand> res = sciTechnologyDemandRepository.findById(id);
            if (res.isPresent()) {
                SciTechnologyDemand sciTechnologyDemand = res.get();
                sciTechnologyDemand.setIsDelete(1);
                Timestamp currentTimestamp = new Timestamp(System.currentTimeMillis());
                sciTechnologyDemand.setDeleteTime(currentTimestamp);
                sciTechnologyDemandRepository.save(sciTechnologyDemand);
            }
        }
    }

    public void download(List<SciTechnologyDemandDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (SciTechnologyDemandDto sciTechnologyDemand : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("企业名称", sciTechnologyDemand.getCompanyName());
            map.put("成立时间", sciTechnologyDemand.getRegistrationTime());
            map.put("企业类型", sciTechnologyDemand.getCompanyType());
            map.put("统一社会信用代码", sciTechnologyDemand.getBusinessLicense());
            //map.put("企业所在区域", sciTechnologyDemand.getCompanyArea());
            map.put("联系人姓名", sciTechnologyDemand.getContacts());
            map.put("职务", sciTechnologyDemand.getJobTitle());
            map.put("联系手机", sciTechnologyDemand.getContactWay());
            map.put("电子邮箱", sciTechnologyDemand.getEmail());
            map.put("通讯地址", sciTechnologyDemand.getAddress());
            map.put("企业简介", sciTechnologyDemand.getDetails());
            map.put("本企业劳模、工匠情况姓名", sciTechnologyDemand.getFirstFinisherName());
            map.put("本企业劳模、工匠情况职务", sciTechnologyDemand.getUnitPosition());
            map.put("本企业劳模、工匠情况劳模工匠人才类型", sciTechnologyDemand.getMaType());
            map.put("所需技术领域", sciTechnologyDemand.getTechnology());
            map.put("需求名称", sciTechnologyDemand.getSlogan());
            map.put("需求类别", sciTechnologyDemand.getRetype());
            map.put("需求描述", sciTechnologyDemand.getHonor());
            map.put("封面", sciTechnologyDemand.getPic());
            map.put("排序", sciTechnologyDemand.getSort());
            map.put("是否h5、小程序展示", sciTechnologyDemand.getIsShow());
            map.put("审核状态", sciTechnologyDemand.getAuditStatus());
            map.put("热度", sciTechnologyDemand.getHot());
            map.put("办理状态", sciTechnologyDemand.getDoStatus());
            map.put("是否允许编辑", sciTechnologyDemand.getIsEdit());
            //map.put("回顾", sciTechnologyDemand.getReview());
            //map.put("记录", sciTechnologyDemand.getRecord());
            map.put("关键字", sciTechnologyDemand.getKeyword());
            map.put("关键字其他", sciTechnologyDemand.getKeywordOther());
            map.put("知识产权数量", sciTechnologyDemand.getZscq());
            map.put("解决企业现场技术问题数量", sciTechnologyDemand.getJjxc());
            map.put("提升职工技能水平的职工数数量", sciTechnologyDemand.getTsjn());
            map.put("创新成果数量", sciTechnologyDemand.getCxcg());
            map.put("产值", sciTechnologyDemand.getCz());
            map.put("利润", sciTechnologyDemand.getProfit());
            map.put("企业所在园区", sciTechnologyDemand.getYq());
            map.put("是否为中小微企业", sciTechnologyDemand.getIsZxw());
            map.put("是否为专精特新企业", sciTechnologyDemand.getIsZj());
            map.put("参加劳模工匠人次", sciTechnologyDemand.getJoinModelCounts());
            map.put("解决问题和开展服务类别", sciTechnologyDemand.getJjProblemType());
            map.put("已解决问题主要内容", sciTechnologyDemand.getYjjProblemContext());
            map.put("产生或预期产生效益(万元)", sciTechnologyDemand.getXy());
            String qyName = "";
            Integer qyId = sciTechnologyDemand.getQyId();
            if (qyId != null) {
                Optional<SciEnterprise> res = sciEnterpriseRepository.findById(qyId);
                if (res.isPresent()) {
                    SciEnterprise sciEnterprise = res.get();
                    qyName = sciEnterprise.getName();
                }
            }
            map.put("所属企业", qyName);
            String orgArea = sciTechnologyDemand.getOrgArea();
            if (orgArea != null) {
                if (orgArea.contains(";")) {
                    String[] split = orgArea.split(";");
                    String str = "";
                    for (String a : split) {
                        str = str + a + "/";
                    }
                    map.put("所属工会", str);
                } else {
                    map.put("所属工会", orgArea);
                }
            } else {
                map.put("所属工会", "");
            }
            String companyAreas = sciTechnologyDemand.getCompanyArea();
            if (companyAreas != null) {
                if (companyAreas.contains(";")) {
                    String[] split = companyAreas.split(";");
                    String str = "";
                    for (String a : split) {
                        str = str + a + "/";
                    }
                    map.put("企业所在区域", str);
                } else {
                    map.put("企业所在区域", companyAreas);
                }
            } else {
                map.put("企业所在区域", "");
            }
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }


    public List<DictDetailDto> getZqxCompanyType() {
        DictQueryCriteria dictQueryCriteria = new DictQueryCriteria();
        dictQueryCriteria.setBlurry("zqx_company_type");
        List<DictDto> list = dictService.queryAll(dictQueryCriteria);
        if (list != null && list.size() == 1) {
            List<DictDetailDto> list1 = dictDetailService.getDictByDictId(list.get(0).getId());
            return list1;
        }
        return null;
    }

    public List<DictDetailDto> getzqxCompanyArea() {
        DictQueryCriteria dictQueryCriteria = new DictQueryCriteria();
        dictQueryCriteria.setBlurry("zqx_company_area");
        List<DictDto> list = dictService.queryAll(dictQueryCriteria);
        if (list != null && list.size() == 1) {
            List<DictDetailDto> list1 = dictDetailService.getDictByDictId(list.get(0).getId());
            return list1;
        }
        return null;
    }

    public List<DictDetailDto> getZqxMaType() {
        DictQueryCriteria dictQueryCriteria = new DictQueryCriteria();
        dictQueryCriteria.setBlurry("zqx_ma_type");
        List<DictDto> list = dictService.queryAll(dictQueryCriteria);
        if (list != null && list.size() == 1) {
            List<DictDetailDto> list1 = dictDetailService.getDictByDictId(list.get(0).getId());
            return list1;
        }
        return null;
    }

    public List<DictDetailDto> getZqxTechnology() {
        DictQueryCriteria dictQueryCriteria = new DictQueryCriteria();
        dictQueryCriteria.setBlurry("zqx_technology");
        List<DictDto> list = dictService.queryAll(dictQueryCriteria);
        if (list != null && list.size() == 1) {
            List<DictDetailDto> list1 = dictDetailService.getDictByDictId(list.get(0).getId());
            return list1;
        }
        return null;
    }

    public List<DictDetailDto> getZqxReType() {
        DictQueryCriteria dictQueryCriteria = new DictQueryCriteria();
        dictQueryCriteria.setBlurry("zqx_re_type");
        List<DictDto> list = dictService.queryAll(dictQueryCriteria);
        if (list != null && list.size() == 1) {
            List<DictDetailDto> list1 = dictDetailService.getDictByDictId(list.get(0).getId());
            return list1;
        }
        return null;
    }

    //@Transactional(rollbackFor = Exception.class)
    public SciTechnologyDemandDto createWithSaveFileWithSci(SciTechnologyDemandAddDto dto) {
        /*Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {
            throw new BadRequestException("用户ID未找到");
        }*/
        /*MultipartFile multipartFile = dto.getFile();
        if (multipartFile == null) {
            throw new BadRequestException("缺少上传的文件");
        }
        // 文件大小验证
        FileUtil.checkSize(properties.getAvatarMaxSize(), multipartFile.getSize());
        // 验证文件上传的格式
        String image = "gif jpg png jpeg";
        String fileType = FileUtil.getExtensionName(multipartFile.getOriginalFilename());
        if (fileType != null && !image.contains(fileType)) {
            throw new BadRequestException("文件格式错误！, 仅支持 " + image + " 格式");
        }
        File file = FileUtil.upload(multipartFile, properties.getSciTechnologyDemandPic());
        String path = Objects.requireNonNull(file).getPath();
        String[] files = path.split("file");*/

        String slogan = dto.getSlogan();
        if (slogan == null) {
            throw new BadRequestException("需求名称为空");
        }
        String companyName = dto.getCompanyName();
        /*if (companyName == null) {
            throw new BadRequestException("企业名称为空");
        }*/


        SciTechnologyDemand resources = new SciTechnologyDemand();
        //resources.setPic("/file" + files[1]);
        resources.setPic(dto.getPic());
        resources.setCompanyName(companyName);
        if (dto.getQyId() != null) {
            Integer qyId = dto.getQyId();
            Optional<SciEnterprise> res = sciEnterpriseRepository.findById(qyId);
            if (res.isPresent()) {
                SciEnterprise sciEnterprise = res.get();
                if (sciEnterprise.getIsDelete() == 1) {
                    throw new BadRequestException("该企业已被删除,请重新选择");
                } else {
                    resources.setQyId(sciEnterprise.getId());
                }
            } else {
                throw new BadRequestException("未找到该企业,请重新选择");
            }
        } else {
            resources.setQyId(null);
        }
        resources.setSlogan(slogan);
        resources.setRegistrationTime(dto.getRegistrationTime());
        resources.setCompanyType(dto.getCompanyType());
        resources.setBusinessLicense(dto.getBusinessLicense());
        //resources.setCompanyArea(dto.getCompanyArea());
        if (dto.getCompanyAreas() != null && dto.getCompanyAreas().length > 0) {
            String last = "";
            for (String a : dto.getCompanyAreas()) {
                last = last + a + ";";
            }
            resources.setCompanyArea(last);
        } else {
            resources.setCompanyArea(null);
        }
        resources.setDoStatus(ppz);
        resources.setContacts(dto.getContacts());
        resources.setJobTitle(dto.getJobTitle());
        resources.setContactWay(dto.getContactWay());
        resources.setEmail(dto.getEmail());
        //resources.setRecord(dto.getRecord());
        resources.setAddress(dto.getAddress());
        resources.setHot(0);
        resources.setZscq(dto.getZscq());
        resources.setJjxc(dto.getJjxc());
        resources.setTsjn(dto.getTsjn());
        resources.setCz(dto.getCz());
        resources.setYq(dto.getYq());
        resources.setIsZxw(dto.getIsZxw());
        resources.setIsZj(dto.getIsZj());
        resources.setJoinModelCounts(dto.getJoinModelCounts());
        resources.setJjProblemType(dto.getJjProblemType());
        resources.setYjjProblemContext(dto.getYjjProblemContext());
        resources.setXy(dto.getXy());
        resources.setProfit(dto.getProfit());
        resources.setCxcg(dto.getCxcg());
        resources.setReview(dto.getReview());
        resources.setIsEdit(0);//默认不可编辑
        resources.setDetails(dto.getDetails());
        resources.setKeywordOther(dto.getKeywordOther());
        if (dto.getKeywords() != null && dto.getKeywords().length > 0) {
            String last = "";
            for (String a : dto.getKeywords()) {
                last = last + a + ";";
            }
            resources.setKeyword(last);
        } else {
            resources.setKeyword(null);
        }
        resources.setUserId(SecurityUtils.getCurrentUserId());
        resources.setFirstFinisherName(dto.getFirstFinisherName());
        resources.setUnitPosition(dto.getUnitPosition());
        if (dto.getMatypes() != null && dto.getMatypes().length > 0) {
            String last = "";
            for (String a : dto.getMatypes()) {
                last = last + a + ";";
            }
            resources.setMaType(last);
        } else {
            resources.setMaType(null);
        }
        //resources.setMaType(dto.getMaType());
        resources.setIsDelete(0);
        resources.setIsShow(0);
        resources.setSort(1);
        resources.setAuditStatus(qxdsh);
        /*if (dto.getOrgArea() != null && !dto.getOrgArea().equals("")) {
            resources.setOrgArea(dto.getOrgArea());//外部传
        } else {
            resources.setOrgArea(orgAreaReturn());
        }*/
        if (dto.getOrgAreas() != null && dto.getOrgAreas().length > 0) {
            //外部传
            String last = "";
            for (String a : dto.getOrgAreas()) {
                last = last + a + ";";
            }
            resources.setOrgArea(last);
        } else {
            //根据登录用户 orgArea进行判断
            resources.setOrgArea(orgAreaReturn());
        }
        resources.setTechnology(dto.getTechnology());
        resources.setRetype(dto.getRetype());
        resources.setHonor(dto.getHonor());

        //TODO 如果企业id不为null的话则查询该企业表里信息替换原来所传参数
        if (resources.getQyId() != null) {
            Optional<SciEnterprise> res = sciEnterpriseRepository.findById(resources.getQyId());
            if (!res.isPresent()) {
                throw new BadRequestException("未查询到该企业,请选择企业");
            }
            SciEnterprise sciEnterprise = res.get();
            //resources.setOrgArea(sciEnterprise.getOrgArea());
            resources.setCompanyArea(sciEnterprise.getCompanyArea());
            resources.setBusinessLicense(sciEnterprise.getCode());
            resources.setYq(sciEnterprise.getDetailAddress());
            String nature = sciEnterprise.getNature();
            //"国有" "民营" "其他"
            if (nature == null) {
                resources.setCompanyType("其他");
            } else {
                if (nature.equals("GY")) {
                    resources.setCompanyType("国有");
                } else if (nature.equals("SY")) {
                    resources.setCompanyType("民营");
                } else {
                    resources.setCompanyType("其他");
                }
            }
        }

        SciTechnologyDemand save = sciTechnologyDemandRepository.save(resources);

        SciTechnologyDemandPpLog sciTechnologyDemandPpLog = new SciTechnologyDemandPpLog();
        sciTechnologyDemandPpLog.setTdId(save.getId());
        sciTechnologyDemandPpLog.setNewStatus(ppz);
        sciTechnologyDemandPpLog.setOldStatus("");//无 - 匹配中
        sciTechnologyDemandPpLogRepository.save(sciTechnologyDemandPpLog);

        //根据id设置sort
        Optional<SciTechnologyDemand> result = sciTechnologyDemandRepository.findById(save.getId());
        if (result.isPresent()) {
            SciTechnologyDemand sciCxResult = result.get();
            sciCxResult.setSort(sciCxResult.getId());
            sciTechnologyDemandRepository.save(sciCxResult);
        }

        List<SciTechnologyDemandInfoAddDto> listSdInfo = dto.getListSdInfo();
        if (listSdInfo != null && listSdInfo.size() > 0) {
            for (SciTechnologyDemandInfoAddDto res : listSdInfo) {
                SciTechnologyDemandInfo sciTechnologyDemandInfo = new SciTechnologyDemandInfo();
                sciTechnologyDemandInfo.setUnitPosition(res.getUnitPosition());
                sciTechnologyDemandInfo.setFirstFinisherName(res.getFirstFinisherName());
                //sciTechnologyDemandInfo.setMaType(res.getMaType());
                if (res.getMaTypes() != null && res.getMaTypes().length > 0) {
                    String last = "";
                    for (String a : res.getMaTypes()) {
                        last = last + a + ";";
                    }
                    sciTechnologyDemandInfo.setMaType(last);
                } else {
                    sciTechnologyDemandInfo.setMaType(null);
                }
                sciTechnologyDemandInfo.setTdId(save.getId());
                sciTechnologyDemandInfoRepository.save(sciTechnologyDemandInfo);
            }
        }

        List<SciTechnologyDemandRecordAddDto> listRecord = dto.getListRecord();
        if (listRecord != null && listRecord.size() > 0) {
            for (SciTechnologyDemandRecordAddDto res : listRecord) {
                SciTechnologyDemandRecord sciTechnologyDemandRecord = new SciTechnologyDemandRecord();
                sciTechnologyDemandRecord.setRecord(res.getRecord());
                sciTechnologyDemandRecord.setGjCounts(res.getGjCounts());
                sciTechnologyDemandRecord.setMyTime(res.getMyTime());
                sciTechnologyDemandRecord.setTdId(save.getId());
                sciTechnologyDemandRecordRepository.save(sciTechnologyDemandRecord);
            }
        }

        //doSaveToSci(save, userId); //不用注册
        SciTechnologyDemandDto sciTechnologyDemandDto = sciTechnologyDemandMapper.toDto(save);
        String matype = sciTechnologyDemandDto.getMaType();
        if (matype != null && matype.contains(";")) {
            String[] array = matype.split(";");
            sciTechnologyDemandDto.setMatypes(array);
        }
        List<SciTechnologyDemandInfo> list2 = sciTechnologyDemandInfoRepository.findByTdId(sciTechnologyDemandDto.getId());
        List<SciTechnologyDemandInfoDto> list3 = sciTechnologyDemandInfoMapper.toDto(list2);
        if (list3 != null && list3.size() > 0) {
            for (SciTechnologyDemandInfoDto info : list3) {
                String maType = info.getMaType();
                if (maType != null && maType.contains(";")) {
                    String[] array = maType.split(";");
                    info.setMaTypes(array);
                } else {
                    String[] array = {};
                    info.setMaTypes(array);
                }
            }
        }
        sciTechnologyDemandDto.setListSdInfo(list3);

        List<SciTechnologyDemandRecord> list5 = sciTechnologyDemandRecordRepository.findByTdId(sciTechnologyDemandDto.getId());
        List<SciTechnologyDemandRecordDto> sciTechnologyDemandRecordDtos = sciTechnologyDemandRecordMapper.toDto(list5);
        sciTechnologyDemandDto.setListRecord(sciTechnologyDemandRecordDtos);
        return sciTechnologyDemandDto;
    }

    //保存至助企行大赛表
    public void doSaveToSci(SciTechnologyDemand dto, Long userId) {
        Optional<User> res = userRepository.findById(userId);
        if (!res.isPresent()) {
            throw new BadRequestException("未找到该用户");
        }
        User user = res.get();
        String myphone = "";
        if (user.getPhone() != null && !user.getPhone().equals("")) {
            myphone = user.getPhone();
        } else {
            myphone = user.getUsername();
        }
        String url = "https://zqx.fzzgsc.com/api/wx/zqx/batchSaveZqxRace";
        String jsonStr = "{\n" +
                "    \"list\": [\n" +
                "        {\n" +
                "            \"loginUsername\": \"" + myphone + "\",\n" +
                "            \"companyName\": \"" + dto.getCompanyName() + "\",\n" +
                "            \"registrationTime\": \"" + dto.getRegistrationTime() + "\",\n" +
                "            \"companyType\": \"" + dto.getCompanyType() + "\",\n" +
                "            \"businessLicense\": \"" + dto.getBusinessLicense() + "\",\n" +
                "            \"companyArea\": \"" + dto.getCompanyArea() + "\",\n" +
                "            \"contacts\": \"" + dto.getContacts() + "\",\n" +
                "            \"jobTitle\": \"" + dto.getJobTitle() + "\",\n" +
                "            \"contactWay\": \"" + dto.getContactWay() + "\",\n" +
                "            \"email\": \"" + dto.getEmail() + "\",\n" +
                "            \"address\": \"" + dto.getAddress() + "\",\n" +
                "            \"details\": \"" + dto.getDetails() + "\",\n" +
                "            \"firstFinisherName\": \"" + dto.getFirstFinisherName() + "\",\n" +
                "            \"unitPosition\": \"" + dto.getUnitPosition() + "\",\n" +
                "            \"maType\": \"" + dto.getMaType() + "\",\n" +
                "            \"technology\": \"" + dto.getTechnology() + "\",\n" +
                "            \"slogan\": \"" + dto.getSlogan() + "\",\n" +
                "            \"retype\": \"" + dto.getRetype() + "\",\n" +
                "            \"honor\": \"" + dto.getHonor() + "\",\n" +
                "            \"pic\": \"" + dto.getPic() + "\"\n" +
                "        }\n" +
                "    ]\n" +
                "}";
        HttpUtils2.post(url, jsonStr);
    }


    public List<AbutmentDataDto> getAbutmentData(List<AbutmentDataDto> list) {
        if (list != null && list.size() > 0) {
            for (AbutmentDataDto dto : list) {
                String demand_product_name = dto.getDemand_product_name();//需求名称
                String jsly_code = dto.getJsly_code();//所需技术领域
                String xqlb_code = dto.getXqlb_code();//需求列别
                String xqlb_other = dto.getXqlb_other();//其他需求类别
                String detail_desc = dto.getDetail_desc();//需求描述
                String related_pictures = dto.getRelated_pictures();//相关图片
                String ent_name = dto.getEnt_name();//企业名称
                String company_type = dto.getCompany_type();//企业类型
                String contact = dto.getContact();//联系人姓名
                String duties = dto.getDuties();//职务
                String contact_number = dto.getContact_number();//联系人手机
                String email = dto.getEmail();//电子邮件
                String address_detail = dto.getAddress_detail();//通讯地址
                String data_id = dto.getData_id();//唯一码
                String companyArea = dto.getCompany_area();//唯一码
                String handle_desc = dto.getHandle_desc();//处理说明
                int handle_type = dto.getHandle_type();//工信厅 1-匹配推送，2-线下解决，3-其他

                List<SciTechnologyDemand> list2 = sciTechnologyDemandRepository.findNormalByDataId(data_id);
                if (list2 != null && list2.size() == 1) {
                    SciTechnologyDemand sciTechnologyDemand = list2.get(0);
                    if (demand_product_name == null) {
                        sciTechnologyDemand.setSlogan("");
                    } else {
                        sciTechnologyDemand.setSlogan(demand_product_name);
                    }
                    sciTechnologyDemand.setTechnology(jsly_code);
                    sciTechnologyDemand.setRetype(xqlb_code);
                    sciTechnologyDemand.setXqlbOther(xqlb_other);
                    sciTechnologyDemand.setHonor(detail_desc);
                    sciTechnologyDemand.setPic(related_pictures);
                    if (ent_name == null) {
                        sciTechnologyDemand.setCompanyName("");
                    } else {
                        sciTechnologyDemand.setCompanyName(ent_name);
                    }
                    sciTechnologyDemand.setCompanyType(company_type);
                    sciTechnologyDemand.setContacts(contact);
                    sciTechnologyDemand.setJobTitle(duties);
                    sciTechnologyDemand.setContactWay(contact_number);
                    sciTechnologyDemand.setEmail(email);
                    sciTechnologyDemand.setAddress(address_detail);
                    sciTechnologyDemand.setCompanyArea(companyArea);
                    sciTechnologyDemand.setHandleDesc(handle_desc);
                    sciTechnologyDemand.setHandleType(handle_type);
                    sciTechnologyDemandRepository.save(sciTechnologyDemand);
                } else {
                    //新增
                    SciTechnologyDemand last = new SciTechnologyDemand();
                    if (demand_product_name == null) {
                        last.setSlogan("");
                    } else {
                        last.setSlogan(demand_product_name);
                    }
                    last.setTechnology(jsly_code);
                    last.setRetype(xqlb_code);
                    last.setXqlbOther(xqlb_other);
                    last.setHonor(detail_desc);
                    last.setHandleDesc(handle_desc);
                    last.setHandleType(handle_type);
                    last.setPic(related_pictures);
                    if (ent_name == null) {
                        last.setCompanyName("");
                    } else {
                        last.setCompanyName(ent_name);
                    }
                    last.setCompanyType(company_type);
                    last.setContacts(contact);
                    last.setJobTitle(duties);
                    last.setContactWay(contact_number);
                    last.setEmail(email);
                    last.setAddress(address_detail);
                    last.setIsDelete(0);
                    last.setIsShow(0);
                    last.setSort(1);
                    last.setHot(0);
                    last.setIsEdit(1);
                    last.setIsEdit(0);
                    last.setUserId(SecurityUtils.getCurrentUserId());
                    last.setAuditStatus(shtg);
                    last.setDoStatus(ppz);
                    last.setDataId(data_id);
                    last.setOrgArea("工信厅;");
                    last.setCompanyArea(companyArea);
                    SciTechnologyDemand save = sciTechnologyDemandRepository.save(last);

                    SciTechnologyDemandPpLog sciTechnologyDemandPpLog = new SciTechnologyDemandPpLog();
                    sciTechnologyDemandPpLog.setTdId(save.getId());
                    sciTechnologyDemandPpLog.setNewStatus(ppz);
                    sciTechnologyDemandPpLog.setOldStatus("");//无 - 匹配中
                    sciTechnologyDemandPpLogRepository.save(sciTechnologyDemandPpLog);
                }
            }
        }
        return list;
    }

    //需求根据企业表，同名绑定其id至劳模表
    public void bindZqxQyId() {
        Boolean flag = true;
        if (flag) {
            List<SciTechnologyDemand> list = sciTechnologyDemandRepository.findNoDelete();
            if (list != null && list.size() > 0) {
                for (SciTechnologyDemand sciTechnologyDemand : list) {
                    String employer = sciTechnologyDemand.getCompanyName();
                    List<SciEnterprise> list2 = sciEnterpriseRepository.queryPassEntertpriseByName("审核通过", "%" + employer + "%");
                    if (list2 != null && list2.size() == 1) {
                        SciEnterprise sciEnterprise = list2.get(0);
                        if (sciEnterprise != null) {
                            sciTechnologyDemand.setQyId(sciEnterprise.getId());
                            sciTechnologyDemandRepository.save(sciTechnologyDemand);
                        }
                    }
                }
            }
        } else {
            throw new BadRequestException("未执行该方法");
        }
    }
}